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开发者_StackOverflow()
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:
Howfor( ; ++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 i
will become too big to fit into a short and will wrap around and become 0 - which will break the loop. Basically USHRT_MAX + 1
yields 0.
So change i
to unsigned short i = 0
and it will be fine.
for ( init, condition, inc )
Your "condition" is i++
. When i++
equals 0 it exits. With a short it happens quite fast.
Do for ( ; ;i++)
for endless loop
精彩评论