In C, what happens when the condition for a for loop aren't met at the beginning? [closed]

泄露秘密 提交于 2019-12-14 00:13:18

问题


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.



来源:https://stackoverflow.com/questions/42708412/in-c-what-happens-when-the-condition-for-a-for-loop-arent-met-at-the-beginning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!