my code is:
#include<stdio.h>
main() {
short int i=0;
for(i<=5 && i>=-1; ++i; i>0)
printf("%d, ",i);
return 0;
}
OUTPUT:-
i don't know from where it starts but end in the sequence
..., -4, -3, -2, -1
can u help me understand the working of this code snippet?
for(i<=5 && i>=-1; ++i; i>0)
is equivalent to:
for(; ++i;)
because i<=5 && i>=-1
and i > 0
expressions have no side-effects.
Now the controlling expression is ++i
, it means the loop is executed until ++i
is evaluated to 0
.
i
is a short
object so ++i
is equivalent to i = (int) i + 1
.
When (int) i + 1
is converted to short
object i
and the value is not representable in a short
, the conversion is implementation defined (see C99, 6.3.1.3p3).
In your implementation the behavior is that when the value is not representable in a short
, it just wraps around and becomes a huge negative value (SHRT_MIN
). The loop is executed repeatedly until the ++i
controlling expression is 0
.