This loop runs only once. Consider:
for(int i=n-1;i<n;n--)
- C
n == 40 , on the first iteration i = 39 . - The condition
i < n is true ( 39 < 40 == true ), so we enter the cycle for the first time. - At the end of the cycle
n is reduced to 39 - The condition
i < n is equal to false ( 39 < 39 == false ), so we do not get a second time through the loop.
Now, what happens if we increase n instead of decreasing? Will it work forever?
for(int i=n-1;i<n;n++)
The answer is "maybe, but probably not":
- In the end,
n reaches the maximum value that can be stored in an integer size, INT_MAX (defined in limits.h , and in my system - 2,147,483,647). - Create an integer greater than
INT_MAX , causing overflow of integers . - The result of an integer overflow signed integer is undefined The , which means that the result can be anything (and, indeed, your program may crash).
However, most of the value of systems is likely to be rounded up to INT_MIN or -2147,483,648.
- If that happens,
i < n is false, and your loop will end.
But, as an integer overflow signed integers is undefined behavior , you can not be sure that this will happen. Itβs better to write your own program to avoid this situation.
If you really want it to work forever - just write:
while(1) { ... }
or
for(;;) { ... }
These two loops have the advantage that they are common ways to write an infinite loop, and so they are easy to read for other programmers.
source share