- C++条件表达式
- 程序实例
- 条件表达式的特性
- 嵌套条件表达式
C++有一个常被用来代替if-else语句的运算符,这个运算符被称为条件运算符(?:),它是C++中唯一一个需要3个操作数的运算符。该运算符的通用格式如下:
// An highlighted block condition ? expression1 : expression2;
如果condition为true,则整个表达式的值为expression1的值;否则,整个表达式的值为expression2的值。
程序实例下述程序使用条件运算符来确定两个值中较大的一个。
// An highlighted block // condit.cpp -- using the conditional operator #includeint main() { using namespace std; int a, b; cout << "Enter two integers: "; cin >> a >> b; cout << "The larger of " << a << " and " << b; int c = a > b ? a : b; // c = a if a > b, else c = b cout << " is "<< c < 下面是程序的运行情况:
Enter two integers: 25 28
The larger of 25 and 28 is 28该程序的关键部分是下面的语句:
// An highlighted block int c = a > b ? a : b;它与下面的语句等效:
// An highlighted block int c; if (a > b) { c = a; } else { c = b; }条件表达式的特性嵌套条件表达式
- 与if-else语句相比,条件运算符更简洁
- 条件运算符生成一个表达式,因此是一个值,可以将其赋给变量或将其放到一个更大的表达式中
- 从可读性来说,条件运算符最适合于简单关系和简单表达式的值
- 当代码变得更复杂时,使用if-else语句来表达更为清晰
下述代码的输出是什么?
// An highlighted block #includeusing std::cout; using std::endl; int main() { const char x[2][20] = {"Jason ", "at your service!n"}; const char* y = "Bourne "; for (int i=0; i < 3; i ++) { cout << ((i<2) ? !i ? x[i] : y : x[1]); } return 0; } 嵌套表达式的正确求解思路是从里往外拆分。
例如如下格式的条件表达式:// An highlighted block condition1 ? condition2 ? expression1 : expression2 : expression3;拆解思路:
// An highlighted block if (condition2) return expression1; else condition1 ? expression2 : expression3;拆解为if-else语句:
// An highlighted block if (condition2) return expression1; else { if(condition1) { return expression2; } else { return expression3; } }所以上述嵌套表达式的程序输出为:
Jason Bourne at your service!
注:文中部分内容出自《C++ Primer Plus》第6版,人民邮电出版社



