Search code examples
cgcccomparisonsizeofunsigned

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


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
}

Solution

  • 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");
        }