#include <stdio.h>
main()
{
if (sizeof(int) > -1)
printf("True");
else
printf("False");
}
ANSWER:
False
but according to the logic sizeof(int)
return 2 and if(2>-1)
return 1 and it should print True.
Why it is behaving otherwise?
The operands of the > operator in the if statement are sizeof(int) and -1 . sizeof(int) is of type size_t , which is guaranteed to be an unsigned integer. In practice, size_t will most likely be at least as big as unsigned int on any system out there. -1 is of type int , which is equivalent to signed int .
sizeof(int) returns the number of bytes used to store an integer. int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer. Since the sizeof operator returns the size of the datatype or the parameter we pass to it.
sizeof returns size_t ( unsigned type) . You are comparing a signed int with an unsigned int . When a signed operand is compared with unsigned one, the signed operand get converted to an unsigned value.
The result of the sizeof operator is of type size_t , an integral type defined in the include file <stddef.
First of all, the value produced by sizeof
is of size_t
which is unsigned
type. NOTE
As the unsigned
type is of higher rank than the signed
type, while performing the comparison, as per the norms of the relation operator, the usual arithmetic conversions are performed, meaning the signed type is promoted to unsigned type.
In your case, the -1
, when considered as unsigned
, represent the highest possible unsigned
value, thus, no wonder
if (sizeof(int) > -1)
Evaluates to false.
Moral of the story: Attempted comparison between a signed
and an unsigned
is expected to produce weird result, just as in your case. You should enable compiler warning and try to solve the issues reported by the compiler.
NOTE:
From C11
, chapter §7.19, <stddef.h>
,
size_t
which is theunsigned
integer type of the result of thesizeof
operator.
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