Блог пользователя shank_punk

Автор shank_punk, история, 9 лет назад, По-английски

Hi guys.

#include <stdio.h>
  int main()
   {
   	   if (sizeof(int) > -1)
           printf("True");
       else
           printf("False");
   return 0;
   }

This outputs False. If I give any negative value , the output is False.

I don't understand why.

Shouldn't it be 4>-1 ?

If I replace -1 with 0,1,2 or 3, The output is True.

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
9 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by shank_punk (previous revision, new revision, compare).

»
9 лет назад, # |
Rev. 3   Проголосовать: нравится +1 Проголосовать: не нравится
cout << (sizeof(int) > -1LL);

Outputs 1(true)

»
9 лет назад, # |
Rev. 3   Проголосовать: нравится +9 Проголосовать: не нравится

It is because sizeof returns usigned integer (size_t). When you have comparison between signed and unsigned integer they are both converted to unsigned. Binary representation of -1 in two's complement is 11...1 (32 times) and it is converted to the bigest possible unsigned int. As a result you have comparison between 4 and biggest possible unsigned int.

Read this for more information.

»
9 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Sir,I am newbie but still i will try to answer...**NOTE TO ALL,PLEASE CORRECT ME IF I AM WRONG** sizeof operator if used to determine size of any data type or expression and it return "size_t" type value which is unsigned int so maybe comparison of signed and unsigned causing the problem.when you do this than it returns correct.