Well it is the famous signed unsigned comparison. Here -1
which is signed number when compared to unsigned numbers - promoted to an unsigned number resulting in a big magnitude value (SIZE_MAX
). So it is always false.
The explanation why there would be type promotion here when comparing:
From standard §6.3.1.8
Otherwise, if the operand that has unsigned integer type has rank
greater or equal to the rank of the type of the other operand, then
the operand with signed integer type is converted to the type of the
operand with unsigned integer type.
Also from §6.5.8 under relational operators
If both of the operands have arithmetic type, the usual arithmetic
conversions are performed.
And what sizeof returns?
Under The sizeof and _Alignof operators §6.5.3.4
The value of the result of both operators is implementation-defined, and its type (an unsigned integer type) is
size_t, defined in (and other headers).
And in section §7.19 under Common definitions
size_t which is the unsigned integer type of the result of the sizeof
operator;
To clarify a bit further when you are converting -1
to size_t
it will have the value (Basically modulo SIZE_MAX+1
)
SIZE_MAX+1+(-1)
Also from standard §6.2.5 (Explaining the conversion)
A computation involving unsigned operands can never overflow, because
a result that cannot be represented by the resulting unsigned integer
type is reduced modulo the number that is one greater than the largest
value that can be represented by the resulting type.
sizeof
will produce asize_t
value, which is unsigned, and not necessarily 4 bytes either. – Dai Dec 25 '17 at 14:33unsigned
floating point types, and anyhow the standard says thatsizeof
returns some unsigned integral type; I don't think it would be illegal for an implementation to returnunsigned char
. Anyhow, this is all irrelevant; all you need to know about the return type ofsize_t
is that it's some unsigned integral type, for which atypedef
(size_t
) is provided in stddef.h. – Matteo Italia Dec 25 '17 at 17:00