C / C ++中while(1)和while(0)之间的区别

在这里,我们将看到在C或C ++中while(1)和while之间有什么区别。while是C或C ++的循环。使用此循环,我们可以检查一个条件,当条件为真时,将执行循环内的语句。

while(1)或while(任何非零值)用于无限循环。暂时没有条件。由于存在1或任何非零值,因此条件始终为true。因此,循环中将永远执行的内容。为了摆脱这个无限循环,我们必须使用条件语句和中断语句。

示例

#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被视为带有错误条件的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