LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 275|回复: 0

条件三元运算符 ( ? )

[复制链接]
发表于 2024-2-19 22:52:56 | 显示全部楼层 |阅读模式
条件运算符计算表达式,如果该表达式的计算结果为 ,则返回一个值,如果表达式的计算结果为 ,则返回另一个值。其语法为:



如果 是 ,则整个表达式的计算结果为 ,否则计算结果为 。truefalsecondition ? result1 : result2conditiontrueresult1result2

7==5 ? 4 : 3     // evaluates to 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3   // evaluates to 4, since 7 is equal to 5+2.
5>3 ? a : b      // evaluates to the value of a, since 5 is greater than 3.
a>b ? a : b      // evaluates to whichever is greater, a or b.  

例如:

// conditional operator
#include <iostream>
using namespace std;

int main ()
{
  int a,b,c;

  a=2;
  b=7;
  c = (a>b) ? a : b;

  cout << c << '\n';
}


在此示例中,是 2,并且是 7,因此要计算的表达式 () 不是 ,因此在问号之后指定的第一个值被丢弃,取而代之的是第二个值(冒号后面的值),即 (值为 7)。aba>btrueb

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表