shank_punk's blog

By shank_punk, history, 7 years ago, In English

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.

 
 
 
 
  • Vote: I like it
  • 0
  • Vote: I do not like it

»
7 years ago, # |
  Vote: I like it 0 Vote: I do not like it

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

»
7 years ago, # |
Rev. 3   Vote: I like it +1 Vote: I do not like it
cout << (sizeof(int) > -1LL);

Outputs 1(true)

  • »
    »
    7 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thanks.

    Can you explain why this output is 0 ? ~~~~~ cout<<(sizeof(int) > -1); ~~~~~

»
7 years ago, # |
Rev. 3   Vote: I like it +9 Vote: I do not like it

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.

»
7 years ago, # |
  Vote: I like it 0 Vote: I do not like it

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.