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=10; 3 int second=20; 4 result=first>second?"true":"false"; 5 6 //執行結果:如果first>second result等於true 如果first<second result等於false