Why is (sizeof(int) > -1) false? [duplicate]

Solution 1:

sizeof(int) has type size_t, which is an unsigned integer type.

-1 has type int, which is a signed integer type.

When comparing a signed integer with an unsigned integer, first the signed integer is converted to unsigned, then the comparison is performed with two unsigned integers.

sizeof(int) > (unsigned int)-1 is false, because (unsigned int)-1 is a very large number on most implementations (equal to UINT_MAX, or the largest number which fits in an unsigned int).

Solution 2:

sizeof

yields a value of an unsigned type (namely size_t).

In sizeof(int) > -1 expression, the usual arithmetic conversion applies and -1 is converted to the unsigned type of sizeof which results in a huge unsigned value greater than -1.

Solution 3:

It's because the sizeof operator returns an unsigned integer type. When compared with a signed integer type, the signed integer is converted to unsigned. So in effect, you were comparing sizeof(int) against the largest possible unsigned integer.

You can force the size to signed by casting:

#include <stdio.h>

int main()
{
    if((int)sizeof(int) > -1)
    {
            printf("\nTrue\n");
    }
    else
    {
            printf("\nFALSE\n");
    }
}