在大多数计算机编程语言中,while 循环是一种控制流语句,它允许根据给定的布尔条件重复执行代码。布尔条件为真或假
while(1)
这是一个无限循环,将一直运行到明确发出 break 语句。有趣的是,不是 while(1),而是任何非零整数都会产生与 while(1) 类似的效果。因此,while(1)、while(2) 或 while(-255) 都只会给出无限循环。
while(1) 的简单用法可以在客户端-服务器程序中。在程序中,服务器在无限循环中运行,以接收客户端发送的数据包。
但实际上,在现实世界中使用 while(1) 是不可取的,因为它会增加 CPU 使用率并且还会阻塞代码,即在手动关闭程序之前无法从 while(1) 中退出。while(1) 可用于条件需要始终为真的地方。
输出
输出
while(1) or while(any non-zero integer)
{
// loop runs infinitely
}
// C program to illustrate while(1)
#include <stdio.h>
int main()
{
int i = 0;
while (1) {
printf("%dn", ++i);
if (i == 5)
break; // Used to come
// out of loop
}
return 0;
}
1 2 3 4 5while(0) 与 while(1) 相反。这意味着条件将永远为假,因此 while 中的代码永远不会被执行。
while(0)
{
// loop does not run
}
// C program to illustrate while(0)
#include<stdio.h>
int main()
{
int i = 0, flag=0;
while ( 0 )
{
// This line will never get executed
printf( "%dn", ++i );
flag++;
if (i == 5)
break;
}
if (flag==0)
printf ("Didn't execute the loop!");
return 0;
}
Didn't execute the loop!