开发者

checking condition in a for loop by ++i

开发者 https://www.devze.com 2023-04-02 03:07 出处:网络
Here is a C program: int main() { short int i = 0; for( ; ++i ; )// <-- how this is checking condition

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:

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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消