0
unsigned int array[5],length = 5;

for(int i = -1; i < length; ++i)
{
    array[i] = i;
    printf("%d\n", array[i]);
}

Output: No Output // nothing is printing

I am expecting It should print the array.

Why no output of this c code ? What is the reason ?

Pankaj Suryawanshi
  • 681
  • 1
  • 9
  • 23

1 Answers1

3

The types of i and length are different (int and unsigned int respectively). So in the comparison i < length, i gets converted to an unsigned int because unsigned int has higher rank as per usual arithmetic conversions.

The value of -1 converted to unsigned int is UINT_MAX. Thus the comparison is equivalent to UINT_MAX < 5 in the first iteration. Which is false and the loop is never entered.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Also note that, even if `length` was signed, an optimizing compiler could still decide to remove the entire loop, because it would invoke undefined behavior. – Felix G May 13 '20 at 08:16
  • 3
    That's exactly what i meant. As it is, the body isn't executed because of the loop condition. However, if `length` was declared as signed, then all possible code paths contain undefined behavior. A fact which many optimizing compilers will happily use to optimize away the entire loop. Usually when talking about UB, people say "literally anything can happen", and while that is indeed what the standard implies, in practice one of the most common side-effects of UB (if not the most common) are unexpected optimizations. – Felix G May 13 '20 at 08:32