When you perform mixed signed vs. unsigned comparison (where signed type is not larger than unsigned one), the comparison is performed in unsigned domain, i.e. the signed operand is implicitly converted to unsigned type.
In your case TOTAL_ELEMENTS
has type size_t
, which is unsigned. That means that your d
is also implicitly converted to size_t
type. So, your d < TOTAL_ELEMENTS
is actually interpreted as (size_t) d < TOTAL_ELEMENTS
or (size_t) -1 < TOTAL_ELEMENTS
.
(size_t) -1
is an extremely large positive value. It is actually the largest possible value of type size_t
. Hence the result you get.
In your case you apparently want a signed comparison. For that you have to explicitly convert the unsigned value to signed type (paying close attention not to cause overflow). For example, this will work "as expected"
if (d < (int) TOTAL_ELEMENTS)
...