Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking condition in a for loop by ++i

Tags:

c

loops

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?

like image 753
Javed Akram Avatar asked Dec 13 '22 09:12

Javed Akram


1 Answers

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.

like image 165
cnicutar Avatar answered Jan 05 '23 00:01

cnicutar