Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 491
Deepak Gautam Avatar asked Dec 17 '22 12:12

Deepak Gautam


2 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");
    }
like image 80
Adrian Mole Avatar answered Dec 31 '22 01:12

Adrian Mole


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.

like image 43
Some programmer dude Avatar answered Dec 31 '22 02:12

Some programmer dude