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

更新於: 30-Jul-2019

3K+ 瀏覽量

開啟你的職業生涯

完成課程,獲得認證

開始
廣告