เรารู้ว่า ternary operator ใช้แทน if..else clause แทนด้วย ?: สัญลักษณ์ '?' เทียบเท่า if และ ':' เทียบเท่า else โปรแกรม 3 ตัวต่อไปนี้อธิบายข้อสังเกตน่าสนใจ
โปรแกรมต่อไปนี้ compile ได้โดยไม่ error Ternary expression return type คาดว่าเป็น float (เหมือน exp2) และ exp3 (literal zero - int type) สามารถ implicit convert เป็น float ได้
#include <iostream>
using namespace std;
int main(){
int test1 = 0;
float fvalue = 3.111f;
cout<< (test1 ? fvalue : 0) << endl;
return 0;
}
โปรแกรมต่อไป compile ไม่ได้ เพราะ compiler หา return type ของ ternary expression ไม่เจอ หรือ implicit conversion ไม่มีระหว่าง exp2 (char array) และ exp3 (int)
#include <iostream>
using namespace std;
int main(){
int test1 = 0;
cout<< test1 ? "A String" : 0 << endl;
return 0;
}
โปรแกรมต่อไปอาจ compile ได้ แต่ fail at runtime Ternary expression return type ถูกจำกัดเป็น (char *) แต่ expression คืนค่า int โปรแกรมจึง fail พยายามพิมพ์ string ที่ address 0
#include <iostream>
using namespace std;
int main(){
int test1 = 0;
cout << (test1 ? "A String" : 0) << endl;
return 0;
}
เราสังเกตได้ว่า exp2 ถูกมองเป็น output type และ exp3 จะ convert เป็น exp2 ที่ runtime ถ้า conversion เป็น implicit compiler จะแทรก stubs สำหรับ conversion ถ้า explicit compiler จะ throw error ถ้า compiler miss จะ fail at runtime