三元运算符 ?: 与 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.