For example, what happens if I say:
for(i = 2; i < 2; i++)
Obviously, this is a useless for loop, but maybe i = a, and a is set by something else. So what happens in this case?
For example, what happens if I say:
for(i = 2; i < 2; i++)
Obviously, this is a useless for loop, but maybe i = a, and a is set by something else. So what happens in this case?
The condition of a for loop is checked before every iteration, including the first one; so your loop's body will never be executed.
In a
for
loop, the condition is evaluated before the first iteration. This means that in your example, the content of the loop would not be executed becausei
is already greater than or equal to2
.Example code path:
i = 2
.i < 2
.i
would still be modified, however, as the variable initialization (i.e.i = 2
) still occurs before the condition is checked.Neither iteration of the loop will be executed.
In fact this loop (provided that the condition has no side effects)
is equivalent to this statement
The way for loop works is it checks for condition (in your case
i < 2
) and executes whatever is between{ }
or whatever code on following linesAs you are initializing
i
to2
the condition fails immediately and nothing executes.Essentially whatever code that is inside of for loop never executes.