C++三元操作符


c++的三元操作符形式:

//條件表達式 ? 表達式1 : 表達式2;

語義:如果“條件表達式”為true,則整個表達式的值就是表達式1,忽略表達式2;如果“條件表達式”為false,則整個表達式的值就是表達式2,等價於if/else語句。

1 if (條件表達式)
2    result = 表達式1;
3 else
4    result = 表達式2;

實例1:

1 int result;
2 int first=10;
3 int second=20;
4 result=first>second?0:1;
5 
6 //執行結果:如果first>second  result=0,如果first<second result=1;

實例2:

1 string  result;
2 int first=103 int second=204 result=first>second?"true":"false";
5 
6 //執行結果:如果first>second result等於true  如果first<second  result等於false

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM