0
void main()
{
    if(sizeof(int) > -1)
        printf("true");
    else
        printf("false");    
}

I expected the output to be true but it is false. Can anybody please explain me the reason for the output.

Venkat
  • 93
  • 1
  • 7

3 Answers3

9

sizeof(int) is of type size_t, which is an unsigned integer type. So in the expression if(sizeof(int) > -1), -1 is converted to an unsigned integer, which is very big.

BTW, use int main instead of the non-standard void main.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
7

sizeof(int) returns size_t which is as unsigned int.

Usual arithmetic conversions are implicitly performed for common type.

int --> unsigned int --> long --> unsigned long --> long long --> unsigned long long --> float --> double --> long double

int value(-1) is converted to unsigned int as part of implicit conversion.

-1 will be represented as 0xFFFF in 16 bit machine(for example).

So expression becomes,

if(sizeof(int) > -1 ) ==> if(2 > 0xFFFF)

And false is printed. I suggest to try if((int)sizeof(int) > -1 ) for proper result.

Jeyaram
  • 9,158
  • 7
  • 41
  • 63
1

The data type of value provided by sizeof is size_t which is (in most machines) an unsigned int/long, therefore, when you compare it with -1, -1 is type promoted to unsigned which then becomes 0xFFF.. , which is the largest value that datatype can hold, therefore your comparison fails.

0xF1
  • 6,046
  • 2
  • 27
  • 50