for(;;)的解释

来源:互联网 发布:学术ppt知乎 编辑:程序博客网 时间:2024/05/16 10:10

通常死循环会这样写

for(;;)

 

无限循环

理论上讲,任何一个循环语句都可以达到死循环的目的,比如 (代码取自udk2014)

/**  Executes an infinite loop.  Forces the CPU to execute an infinite loop. A debugger may be used to skip  past the loop and the code that follows the loop must execute properly. This  implies that the infinite loop must not cause the code that follow it to be  optimized away.**/CpuDeadLoop (  VOID  ){  volatile UINTN  Index;  for (Index = 0; Index == 0;);}

 

一般我们是用for 来达到这个目的,当for 循环的判断条件(conditional expression)为空的时候,就是无限循环。

就像:

for(; ; ) printf("列个循环会永远跑下克.\n");

when the conditional expression is absent. it is assumed to be true.

原因是这样子的,当判断条件没有时,C语言认为这个条件一直为真,当然你可能还有

初始化的语句以及自增语句,但是C程序员通常使用for(;;) 来做成一个无限循环。

 

事实上,for(;;) 并不能保证无限循环,因为有break 语句,任何时候,遇到break语

句,都会立即跳出循环。

举个例子:

 

#include <stdio.h>main(){char ch = '\0';for(;;)for (; ; ) {ch = getchar(); /* get a character */if (ch == 'A') break; /* exit the loop */}printf("you typed an A");}

这个程序会一直跑下去,直到你在键盘上按了一个A。

 

for 语句是这样的

for (initialization; condition; increment)

    statement;

initialization 语句只会执行一次,condition 在每一次循环之前都会去执行一次,当条件不成立的时候,for 循环结束,

increment 语句每次在每一次cicle 结束的时候执行一次,如果statement 里面没有continue, 那么

for (initialization; condition; increment) statement

相当于

 

initialization;

while (condition) {

       statement

      increment;

}

 

在最开始的例子里面, 因为Index 始终等于0,相当于while (1) {}

所以,做到了DeapLoop.

 


 

 

0 0
原创粉丝点击