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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With