A riddle (in C)

Solution 1:

The problem is that (TOTAL_ELEMENTS-2) is an unsigned value. When you make the comparison d <= (TOTAL_ELEMENTS-2), both values are converted to unsigned values, and the result is false.

In your second example, x is signed so there is no problem.

Solution 2:

The sizeof operator yields a result of type size_t. In the first version, you are comparing an int (signed) against a size_t (unsigned).

In the second version, you convert the size_t expression to an int by assigning it, and hence both operands of the comparison are of the same type.

Solution 3:

One another way of seeing this problem as follow

#include<stdio.h>

int main() {

int i = -5;
unsigned int j = 6;

if(i < j)
  printf("-5 is less than 6");
else
  printf("-5 is greater than 6");

return 0;
}

Output is:

-5 is greater than 6

Reason: Comparing unsigned integer with signed integer will always return false.

In the questioner case the sizeof returns unsigned data type but it is compared with signed data type (- is a bug)