Here is a C program:
int main()
{
short int i = 0;
for( ; ++i ; ) // <-- how this is checking condition
printf("%u,", i);
return 0;
}
from the above program I thought that this will go for an endless loop as in for() there is nothing to check the condition and to come out from loop.
but I was wrong, it is not an endless loop.
My question:
How for( ; ++i ; ) is checking condition in the above program?
The program is wrong as it overflows a signed int, which is undefined behavior in C. In some environments it will result in an endless loop, but many compilers implement signed overflow the same way they implement unsigned overflow.
In case signed overflow is implementd like unsigned overflow, at some point
iwill become too big to fit into a short and will wrap around and become 0 – which will break the loop. BasicallyUSHRT_MAX + 1yields 0.So change
itounsigned short i = 0and it will be fine.