What is the reason behind the "False" output of this code?

Viewed 88

This C code gives output "False" and the else block is executing.

The value of sizeof(int) is 4 but the value of sizeof(int) > -1 is 0.

I don't understand what is happening.

#include <stdio.h>
void main()
{
    if (sizeof(int) > -1 )
    {
       printf("True");
    }
    else
    {
        printf("False");
    }
    printf("\n%d", (sizeof(int)) ); //output: 4
    printf("\n%d", (sizeof(int) > -1) ); //output: 0
}
3 Answers

Your sizeof(int) > -1 test is comparing two unsigned integers. This is because the sizeof operator returns a size_t value, which is of unsigned type, so the -1 value is converted to its 'equivalent' representation as an unsigned value, which will actually be the largest possible value for an unsigned int.

To fix this, you need to explicitly cast the sizeof value to a (signed) int:

    if ((int)sizeof(int) > -1) {
        printf("True");
    }

The sizeof operator gives a size_t result.

And size_t is an unsigned type while -1 is not.

That leads to problem when converting -1 to the same type as size_t (-1 turns into a very large number, much larger than sizeof(int)).

Since sizeof returns an unsigned value (which by definition can't be negative), a comparison like yours makes no sense. And besides standard C doesn't allow zero-sized objects or types, so even sizof(any_type_or_expression) > 0 will always be true.

You have to be careful when mixing signed and unsigned values in expressions (and sizeof yields a size_t, which is unsigned).

In a fair number of cases (including this one) the compiler will convert both values to the same type before carrying out operations on them--and when you mix signed and unsigned values, that same type will usually be the unsigned type involved. So what happens in this case is that the -1 gets converted to an unsigned--and when converted to an unsigned value, -1 always converts to the largest value that unsigned type can hold.

From there, the rest is probably fairly clear, I'd guess.

Related