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.
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
.
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.
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.