吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C语言中while(1)和while(0)的区别

C语言中while(1)和while(0)的区别

来源:网络 | 更新时间:2022-01-14 08:15:27
在大多数计算机编程语言中,while 循环是一种控制流语句,它允许根据给定的布尔条件重复执行代码。布尔条件为真或假 while(1) 这是一个无限循环,将一直运行到明确发出 break 语句。有趣的是,不是 while(1),而是任何非零整数都会产生与 while(1) 类似的效果。因此,while(1)、while(2) 或 while(-255) 都只会给出无限循环。  
while(1) or while(any non-zero integer)
{ 
// loop runs infinitely
}
while(1) 的简单用法可以在客户端-服务器程序中。在程序中,服务器在无限循环中运行,以接收客户端发送的数据包。  但实际上,在现实世界中使用 while(1) 是不可取的,因为它会增加 CPU 使用率并且还会阻塞代码,即在手动关闭程序之前无法从 while(1) 中退出。while(1) 可用于条件需要始终为真的地方。 
// 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
5
while(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!
   

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com