【C++】学习笔记二十四——?:运算符

来源:互联网 发布:知乎的功能 编辑:程序博客网 时间:2024/05/21 17:02

条件运算符(?:)

  条件运算符(?:)常被用来代替if else语句,它是C++唯一一个需要3个操作数的运算符。该运算符的通用格式如下:

expression1 ? expression2 : expression3 

  如果expression1为true,则整个表达式的值为expression2的值;否则,整个表达式的值为expression3的值。
 
  下面两个示例演示了该运算符是如何工作的:

5>3 ? 10 : 12           //5>3为true,所以表达式的值为103 == 9 ? 25: 18         //3 == 9为假,所以表达式的值为18 

 
 
程序6.9

#include<iostream>int main(){    using namespace std;    int a, b;    cout << "Enter two integers: ";    cin >> a >> b;    cout << "The lager of " << a << " and " << b;    int c = a > b ? a : b;    cout << " is " << c << endl;    system("pause");    return 0;}

这里写图片描述
 
 
  与if else语句相比,条件运算符更简洁。这两种方法之间的区别是:条件运算符生成一个表达式,因此是一个值,可以将其赋给变量或将其放大一个更大的表达式中。
  
  一个技巧是将条件表达式嵌套在另一个条件表达式中:

const char x[2][20] = {"Jason ","at your service\n"};const char * y = "Quillstone ";for (int i = 0; i < 3; i++)    cout<<((i < 2) ? !i ? x[i] : y :x[1]);

这是一种费解的方式,他按下面的顺序打印3个字符串:

Jason Quillstone at your service
0 0