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

2019-09-30 07:55发布

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?

4条回答
老娘就宠你
2楼-- · 2019-09-30 08:07

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楼-- · 2019-09-30 08:12

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.

查看更多
可以哭但决不认输i
4楼-- · 2019-09-30 08:15

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;
查看更多
做自己的国王
5楼-- · 2019-09-30 08:26

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.

查看更多
登录 后发表回答