Cprogramming 简明教程

C - Infinite Loop

C language 中,一个 infinite loop (或一个 endless loop )是一个永不结束的循环结构,它可以永远执行一组语句而不终止循环。它有一个真条件,使程序可以连续运行。

In C language, an infinite loop (or, an endless loop) is a never-ending looping construct that executes a set of statements forever without terminating the loop. It has a true condition that enables a program to run continuously.

Flowchart of an Infinite Loop

如果程序流无条件地定向到任何前一步骤,则会创建一个无限循环,如下面的流程图所示:

If the flow of the program is unconditionally directed to any previous step, an infinite loop is created, as shown in the following flowchart −

flowchart of infinite loop

无限循环很少有意创建。在嵌入式无头系统和服务器应用程序中,应用程序在无限循环中运行以侦听客户端请求。在其他情况下,无限循环主要是由于无意的编程错误而创建的。

An infinite loop is very rarely created intentionally. In case of embedded headless systems and server applications, the application runs in an infinite loop to listen to the client requests. In other circumstances, infinite loops are mostly created due to inadvertent programming errors.

How to Create an Infinite Loop in C?

要创建无限循环,您需要使用其中一个 loop constructs (while、do while 或 for)将非零值用作测试条件。通常,1 用作测试条件,您可以使用任何非零值。非零值被认为是真的。

To create an infinite loop, you need to use one of the loop constructs (while, do while, or for) with a non-zero value as a test condition. Generally, 1 is used as the test condition, you can use any non-zero value. A non-zero value is considered as true.

Example

#include <stdio.h>

int main() {
  while (1)
  {
    printf("Hello World");
  }

  return 0;
}
Hello WorldHello WorldHello WorldHello WorldHello WorldHello World
Hello WorldHello WorldHello WorldHello WorldHello WorldHello World
Hello WorldHello WorldHello ...

Types of Infinite Loops in C

在 C 语言中,无限 while、无限 do while 和无限 for 是三种无限循环。这些循环会不断执行代码语句。让我们了解一下使用所有循环构造来实现无限循环。

In C language, infinite while, infinite do while, and infinite for are the three infinite loops. These loops execute the code statement continuously. Let us understand the implementation of infinite loops using all loop constructs.

Infinite While Loop

while 关键字用于形成计数循环。循环计划重复执行,直到 variable 的值连续递增为预定义值为止。然而,如果程序员忘记在循环体中放置递增语句,则根本不会达到测试条件,因此它会变成无穷无尽的或无限的。

The while keyword is used to form a counted loop. The loop is scheduled to repeat till the value of some variable successively increments to a predefined value. However, if the programmer forgets to put the increment statement within the loop body, the test condition doesn’t arrive at all, hence it becomes endless or infinite.

请看以下示例:

Take a look at the following example −

#include <stdio.h>

// infinite while loop
int main(){

   int i = 0;
   while (i <= 10){
      // i++;
      printf("i: %d\n", i);
   }
   return 0;
}

Output

由于此处的递增语句被注释掉了,“i”的值会继续保持“0”,因此输出会持续显示“i: 0”,直到你强制停止执行为止。

Since the increment statement is commented out here, the value of "i" continues to remain "0", hence the output shows "i: 0" continuously until you forcibly stop the execution.

i: 0
i: 0
i: 0
...
...

while 关键字的括号中有一个布尔表达式,该表达式最初计算为 True,最终预计将变为 False。请注意,在 C 语言中,任何非零数字均被视为 True。因此,以下 while 循环是一个无限循环:

The parenthesis of while keyword has a Boolean expression that initially evaluates to True, and is eventually expected to become False. Note that any non-zero number is treated as True in C. Hence, the following while loop is an infinite loop:

#include <stdio.h>

// infinite while loop
int main(){

   while(1){
      printf("Hello World \n");
   }
   return 0;
}

Output

它会不断打印“Hello World”。

It will keep printing "Hello World" endlessly.

Hello World
Hello World
Hello World
...
...

while 循环的 syntax 如下所示:

The syntax of while loop is as follows −

while (condition){
   . . .
   . . .
}

请注意, while 前面没有分号符号,表示后面的代码块(在大括号内)是循环主体。如果我们放置一个分号,编译器会将此视为没有主体的循环,因此 while 条件永远不会满足。

Note that the there is no semicolon symbol in front of while, indicating that the following code block (within the curly brackets) is the body of the loop. If we place a semicolon, the compiler treats this as a loop without body, and hence the while condition is never met.

在下面的代码中,循环块中放置了一个递增语句,但由于 while 前面的分号,循环会变成无限循环。

In the following code, an increment statement is put inside the loop block, but because of the semicolon in front of while, the loop becomes infinite.

#include <stdio.h>

// infinite while loop
int main(){

   int i = 0;
   while(i < 10);{
      i++;
      printf("Hello World \n");
   }
   return 0;
}

Output

When the program is run, it won't print the message "Hello World". There is no output because the while loop becomes an infinite loop with no body.

Infinite For Loop

C 语言中的 for loop 用于在每次迭代中将变量的值从其初始值增加到最终值,从而执行代码块的迭代。

The for loop in C is used for performing iteration of the code block for each value of a variable from its initial value to the final value, incrementing it on each iteration.

看看它的语法:

Take a look at its syntax −

for (initial val; final val; increment){
   . . .
   . . .
}

请注意, for 语句中的所有三个子句都是可选的。因此,如果省略指定要测试的最终值的中间子句,则循环会变成无限循环。

Note that all the three clauses of the for statement are optional. Hence, if the middle clause that specifies the final value to be tested is omitted, the loop turns infinite.

#include <stdio.h>

// infinite for loop
int main(){

   int i;
   for(i=1; ; i++){
      i++;
      printf("Hello World \n");
   }
   return 0;
}

Output

程序不断打印 Hello World,直到你强制停止它,因为它在每次迭代中没有递增 “i” 的效果。

The program keeps printing Hello World endlessly until you stop it forcibly, because it has no effect of incrementing "i" on each turn.

Hello World
Hello World
Hello World
...
...

你还可以构造一个 for 循环来递减循环变量的值。在那种情况下,初始值应该大于最终测试值, for 中的第三个子句必须是一个递减语句(使用 “--” 运算符)。

You can also construct a for loop for decrementing the values of a looping variable. In that case, the initial value should be greater than the final test value, and the third clause in for must be a decrement statement (using the "--" operator).

如果初始值小于最终值且第三个语句是递减,则循环会变成无限循环。如果初始值更大,但你错误地使用了递增语句,则循环仍然会变成无限循环。

If the initial value is less than the final value and the third statement is decrement, the loop becomes infinite. The loop still becomes infinite if the initial value is larger but you mistakenly used an increment statement.

因此, for 循环都会导致无限循环。

Hence, both the for loops result in an infinite loop.

请看以下示例:

Take a look at the following example −

#include <stdio.h>

int main(){

  // infinite for loop
  for(int i = 10; i >= 1; i++){
    i++;
    printf("Hello World \n");
  }
}

Output

程序会在无限循环中打印一系列“Hello World”:

The program will print a series of "Hello World" in an infinite loop −

Hello World
Hello World
Hello World
...
...

请看以下示例:

Take a look at the following example −

#include <stdio.h>

int main(){

  // infinite for loop
  for(int i = 1; i <= 10 ; i--){
    i++;
    printf("Hello World \n");
  }
}

Output

程序会在循环中不断打印“Hello World”:

The program keeps printing "Hello World" in a loop −

Hello World
Hello World
Hello World
...
...

如果括号中的所有三个语句都是空白的,显然循环是一个无限循环,因为没有条件要测试。

If all the three statements in the parenthesis are blank, the loop obviously is an infinite loop, as there is no condition to test.

#include <stdio.h>

int main(){

   int i;

   // infinite for loop
   for ( ; ; ){
      i++;
      printf("Hello World \n");
   }
}

Output

程序在一个无限循环中打印“Hello World”:

The program prints "Hello World" in an endless loop −

Hello World
Hello World
Hello World
...
...

Infinite Do While Loop

也可以使用 do-while loop 构造来实现一个无限循环。您必须使用 1 作为 while 的测试条件。

An infinite loop can also be implemented using the do-while loop construct. You have to use 1 as the test condition with the while.

以下示例演示了使用 do while 实现无限循环:

The following example demonstrates an infinite loop using do while:

#include <stdio.h>

int main() {
  do
  {
    printf("Hello World\n");
  } while (1);

  return 0;
}
Hello World
Hello World
Hello World
Hello World
...
...

How to Break an Infinite Loop in C?

编程中可能存在某些需要通过无条件 whilefor 语句开始,但随后需要通过放置条件 break statement 来提供终止循环方式的情况。

There may be certain situations in programming where you need to start with an unconditional while or for statement, but then you need to provide a way to terminate the loop by placing a conditional break statement.

在以下程序中, for 中没有测试语句,但我们使用 break 语句使其成为一个有限循环。

In the following program, there is no test statement in for, but we used a break statement to make it a finite loop.

#include <stdio.h>

int main(){

  // infinite while loop
  for(int i = 1; ; ){
    i++;
    printf("Hello World \n");

    if(i == 5)
      break;
  }
  return 0;
}

Output

当计数器变量达到 5 时,该程序将打印“Hello World”。

The program prints "Hello World" till the counter variable reaches 5.

Hello World
Hello World
Hello World
Hello World

How to Stop an Infinite Loop Forcefully in C?

当程序进入无限循环时,它并不会自行停止。必须强制停止它。根据 operating system 的不同,按“Ctrl + C”或“Ctrl + Break”或任何其他组合键即可完成此操作。

When the program enters an infinite loop, it doesn’t stop on its own. It has to be forcibly stopped. This is done by pressing "Crtrl + C" or "Ctrl + Break" or any other key combination depending on the operating system.

Example

以下 C 程序会进入一个无限循环 −

The following C program enters in an infinite loop −

#include <stdio.h>

int main(){

   // local variable definition
   int a = 0;

   // do loop execution
   LOOP:
      a++;
      printf("a: %d\n", a);
         goto LOOP;

   return 0;
}

Output

执行时,上述程序将从 1 开始打印“a”的递增值,但它不会停止。必须通过按“Ctrl + Break”键强制停止它。

When executed, the above program prints incrementing values of "a" from 1 onwards, but it doesn’t stop. It will have to be forcibly stopped by pressing "Ctrl + Break" keys.

a: 1
a: 2
...
...
a: 10
a: 11
...
...

无限循环大多是编程错误的结果而意外创建的。即使循环关键字未指定终止条件,也必须使用 break 关键字终止循环。

Infinite loops are mostly unintentionally created as a result of programming bug. Even if the looping keyword doesn’t specify the termination condition, the loop has to be terminated with the break keyword.