
條件運算子 (conditional operator) 是 C++ 裡唯一的三元運算子 (ternary operator) ?: ,需要三個運算元,三者均可為運算式,形式如下
expr1?expr2:expr3
若運算式 expr1 為真,運算結果會是運算式 expr2 計算出的值,若為假,運算結果則是運算式 expr3 計算出的值。
條件運算子通常利用在需要二選一的情況下,例如比較兩個整數取較大的值
| 001 | #include <iostream> |
| 002 | |
| 003 | int main() { |
| 004 | int a = 22; |
| 005 | int b = 34; |
| 006 | |
| 007 | std::cout << "a = " |
| 008 | << a |
| 009 | << std::endl; |
| 010 | std::cout << "b = " |
| 011 | << b |
| 012 | << std::endl; |
| 013 | std::cout << (a > b ? a : b) |
| 014 | << " is bigger" |
| 015 | << std::endl; |
| 016 | |
| 017 | return 0; |
| 018 | } |
| 019 | |
| 020 | /* Kaiching Chang |
| 021 | u0410_1.cpp |
| 022 | 2014-02 */ |
編譯後執行,結果如下
| $ g++ u0410_1.cpp |
| $ ./a.out |
| a = 22 |
| b = 34 |
| 34 is bigger |
| $ |
也可以利用在字串中依性別選字
| 001 | #include <iostream> |
| 002 | |
| 003 | int main() { |
| 004 | int sex1 = 0; |
| 005 | int sex2 = 1; |
| 006 | |
| 007 | std::cout << (sex1 ? "She" : "He") |
| 008 | << " is here." |
| 009 | << std::endl; |
| 010 | std::cout << (sex2 ? "She" : "He") |
| 011 | << " is running." |
| 012 | << std::endl; |
| 013 | |
| 014 | return 0; |
| 015 | } |
| 016 | |
| 017 | /* Kaiching Chang |
| 018 | u0410_2.cpp |
| 019 | 2014-02 */ |
編譯後執行,結果如下
| $ g++ u0410_2.cpp |
| $ ./a.out |
| He is here. |
| She is running. |
| $ |
條件運算子有時可用來簡化 if-else 陳述,如以下程式
| 001 | #include <iostream> |
| 002 | |
| 003 | int main() { |
| 004 | int a = 22; |
| 005 | int b = 34; |
| 006 | int max; |
| 007 | |
| 008 | if (a > b) { |
| 009 | max = a; |
| 010 | } |
| 011 | else { |
| 012 | max = b; |
| 013 | } |
| 014 | |
| 015 | std::cout << "max = " |
| 016 | << max |
| 017 | << std::endl; |
| 018 | |
| 019 | return 0; |
| 020 | } |
| 021 | |
| 022 | /* Kaiching Chang |
| 023 | u0410_3.cpp |
| 024 | 2014-02 */ |
if-else 的部份便可用以下來取代
| max = (a > b) ? a : b; |
continue ...
沒有留言:
張貼留言