In C, what happens when the condition for a for lo

2019-09-30 07:23发布

问题:

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?

回答1:

Neither iteration of the loop will be executed.

In fact this loop (provided that the condition has no side effects)

for(i = 2; i < 2; i++) { /* ... */ }

is equivalent to this statement

i = 2;


回答2:

The condition of a for loop is checked before every iteration, including the first one; so your loop's body will never be executed.



回答3:

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 lines

As you are initializing i to 2 the condition fails immediately and nothing executes.

Essentially whatever code that is inside of for loop never executes.



回答4:

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 because i is already greater than or equal to 2.

Example code path:

  1. Set i = 2.
  2. Check if i < 2.
  3. Exit loop because step 2 evaluated to false.

i would still be modified, however, as the variable initialization (i.e. i = 2) still occurs before the condition is checked.