sizeof() operator in if-statement
Solution 1:
-
sizeof
is not a function, it's an operator. The parentheses are not part of the operator's name. - It's failing because the value generated has the unsigned type
size_t
, which causes "the usual arithmetic conversions" in which-1
is converted to unsigned, in which case it's a very large number.
Basically you're comparing 4 > 0xffffffffu
, or something close to that at least. See this question for details.
Solution 2:
Unsigned and signed integer promotion (rather "usual arithmetic conversions", to be more precise). sizeof
yields a value of type size_t
, and when compared to an unsigned value (which size_t
is), -1 is promoted to that type, and overflows and becomes huge.
Unsigned integer overflow has well-defined behavior and is to be taken as modulo 2 ^ width
, where width
is the number of bits in the particular unsigned integer type. So, if you have a 32-bit wide size_t
and int
, for example, your comparison will be equivalent with
if (4 > 4294967295u)
which is obviously false.
Solution 3:
- The operands of the > operator in the if statement are
sizeof(int)
and-1
. -
sizeof(int)
is of typesize_t
, which is guaranteed to be an unsigned integer. In practice,size_t
will most likely be at least as big asunsigned int
on any system out there. -
-1
is of typeint
, which is equivalent tosigned int
. - No integer promotions occur, as both operands are of large enough integer types.
- Then the two operands are balanced according to a C rule formally called the usual arithmetic conversions.
These state (C11 6.3.1.8):
...
Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
- The latter of the above will happen, since a (signed)
int
cannot fit all values of asize_t
. - Thus
-1
is converted to an unsigned integer. In practice,size_t
is most likely equivalent to either unsigned int or unsigned long. Whatever happens when you store -1 in such a variable is implementation-defined behavior. - On a two's complement computer (99.9% of all computers in the world), -1 will be interpreted as
0xFFFFFFFF
(the number of FF depends on the size of an int on the given system). -
4 > 0xFFFFFFFF
evaluates to false.
Solution 4:
Sizeof is an operator that results in an unsigned long int. Hence, when you compare unsigned long int with -1, which is stored as 0xffffffff
(size of int is 4 bytes).
-1 is signed integer by default. But, in comparison between signed int and unsigned int, the compiler goes with implicit typecasting of signed int to unsigned int. This results in unsigned -1 to be approximately equal to 4.6giga value.
Hence, the output is false
.