This loop only runs once. Consider:
for(int i=n-1;i<n;n--)
- With
n == 40
, on the first iteration, i = 39
.
- The condition
i < n
is true (39 < 40 == true
), so we go in to the loop for the first time.
- At the end of the first loop,
n
gets decremented to 39
- The condition
i < n
is false (39 < 39 == false
), so we don't get a second time through the loop.
Now, what happens if we make n
increase instead of decrease? Will that run forever?
for(int i=n-1;i<n;n++)
The answer is "maybe, but probably not":
- Eventually,
n
will reach the largest value that can be stored in an integer, INT_MAX
(defined in limits.h
, and on my system it is 2,147,483,647).
- Making an integer larger than
INT_MAX
causes integer overflow.
- The result of integer overflow on a signed integer is undefined, which means the result could be anything (and indeed, your program could crash).
On most systems, however, the value will probably wrap around to INT_MIN
, or -2,147,483,648.
- If this happens,
i < n
will be false, and your loop will terminate.
But, since integer overflow on signed integers is undefined behaviour, you can't be sure that this will happen. It is better to write your program to avoid this situation.
If you really want it to run 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 for other programmers to read.