C++ if 語句



一個if語句由一個布林表示式後跟一個或多個語句組成。

語法

C++ 中 if 語句的語法為:

if(boolean_expression) {
   // statement(s) will execute if the boolean expression is true
}

如果布林表示式計算結果為true,則將執行 if 語句內的程式碼塊。如果布林表示式計算結果為false,則將執行 if 語句結束後的第一組程式碼(在閉合花括號之後)。

流程圖

C++ if statement

示例

#include <iostream>
using namespace std;
 
int main () {
   // local variable declaration:
   int a = 10;
 
   // check the boolean condition
   if( a < 20 ) {
      // if condition is true then print the following
      cout << "a is less than 20;" << endl;
   }
   cout << "value of a is : " << a << endl;
 
   return 0;
}

當以上程式碼被編譯和執行時,它會產生以下結果:

a is less than 20;
value of a is : 10
廣告