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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With