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?
is equivalent to:
because
i<=5 && i>=-1andi > 0expressions have no side-effects.Now the controlling expression is
++i, it means the loop is executed until++iis evaluated to0.iis ashortobject so++iis equivalent toi = (int) i + 1.When
(int) i + 1is converted toshortobjectiand the value is not representable in ashort, 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++icontrolling expression is0.