C/C++ 中 while(1) 和 while(0) 的区别
在这里我们将了解 C 或 C++ 中 while(1) 和 while(0) 的区别。while 是 C 或 C++ 中的循环。使用此循环,我们可以检查一个条件,只要条件为 true,循环内的语句就会执行。
while(1) 或 while(任何非零值) 用于无限循环。对于 while 没有条件。由于存在 1 或任何非零值,因此条件始终为 true。因此,存在于循环中的内容将永远执行。要退出此无限循环,我们必须使用条件语句和 break 语句。
示例
#include<iostream>
using namespace std;
main(){
int i = 0;
cout << "Starting Loop" << endl;
while(1){
cout << "The value of i: " << ++i <<endl;
if(i == 10){ //when i is 10, then come out from loop
break;
}
}
cout << "Ending Loop" ;
}输出
Starting Loop The value of i: 1 The value of i: 2 The value of i: 3 The value of i: 4 The value of i: 5 The value of i: 6 The value of i: 7 The value of i: 8 The value of i: 9 The value of i: 10 Ending Loop
同样,while(0) 被视为条件为 false 的 while。因此,这种循环是无用的。它永远不会执行内部语句,因为 0 被视为 false。
示例
#include<iostream>
using namespace std;
main(){
int i = 0;
cout << "Starting Loop" << endl;
while(0){
cout << "The value of i: " << ++i <<endl;
if(i == 10){ //when i is 10, then come out from loop
break;
}
}
cout << "Ending Loop" ;
}输出
Starting Loop Ending Loop
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP