三元運算子 ?: 與 C/C++ 中的 if…else


我們知道三元運算子是條件運算子。使用此運算子,我們可以檢查一些條件並根據該條件執行某些任務。如果不使用三元運算子,我們還可以使用 if-else 條件來執行同樣的操作。

在大多數情況下,三元運算子和 if-else 條件的作用相同。有時候在某些情況下,我們無法使用 if-else 條件。在這種情況下,我們必須使用三元運算子。這種情況之一是將一些值分配給一些常量變數。我們無法使用 if-else 條件將值分配給常量變數。但是我們可以使用三元運算子將值分配給一些常量變數

示例程式碼

#include<iostream>
using namespace std;
main() {
   int a = 10, b = 20;
   const int x;
   if(a < b) {
      x = a;
   } else {
      x = b;
   }
   cout << x;
}

輸出

This program will not be compiled because we are trying to use the
constant variable in different statement, that is not valid.

使用三元運算子,它將起作用。

示例程式碼

#include<iostream>
using namespace std;
main() {
   int a = 10, b = 20;
   const int x = (a < b) ? a : b;
   cout << x;
}

輸出

10

更新於:2019 年 7 月 30 日

676 次瀏覽

開啟你的職業生涯

完成教程獲得認證

開始
廣告
© . All rights reserved.