บทนำ
Ternary operator คือ conditional operator ใช้ตรวจสอบเงื่อนไขและทำงานตามเงื่อนไขนั้น โดยไม่ใช้ if-else ก็ได้
ผลของ ternary operator และ if-else เหมือนกันในกรณีส่วนใหญ่ แต่บางครั้งไม่สามารถใช้ if-else ได้ ต้องใช้ ternary operator เช่น การกำหนดค่าให้ constant variable ไม่ได้ด้วย if-else แต่ทำได้ด้วย ternary operator
ตัวอย่างที่ไม่ทำงานด้วย if-else
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
const int x;
if (a < b) {
x = a;
} else {
x = b;
}
cout << x;
return 0;
}
ผลลัพธ์
โปรแกรมจะคอมไพล์ไม่ผ่าน เพราะพยายามใช้ constant variable ในคำสั่งแยกต่างหาก ซึ่งไม่ถูกต้อง
ตัวอย่างที่ทำงานด้วย Ternary Operator
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
const int x = (a < b) ? a : b;
cout << x;
return 0;
}
ผลลัพธ์
10