ตัวดำเนินการ ? เรียกว่า Ternary Operator หรือ Conditional Operator ต้องการ 3 Operands รูปแบบ Condition ? Expr1 : Expr2 ลดโค้ดและเพิ่มประสิทธิภาพ
รูปแบบ
Expression1 ? Expression2 : Expression3
ตัวอย่าง 1
#include <stdio.h>
int main() {
int a = -1;
double b = 26.4231;
int c = a ? printf("True value : %lf", b) : printf("False value : 0");
return 0;
}
ผลลัพธ์
True value : 26.423100
a = -1 เป็น True (Non-zero) จึงรัน Expression2
ตัวอย่าง 2
#include <stdio.h>
int main() {
int x = -1, y = 3;
double b = x + y + 0.5;
int c = x < y ? printf("True value : %lf", b) : printf("False value : 0");
return 0;
}
ผลลัพธ์
True value : 2.500000
คำเตือน
- Expression2 และ Expression3 ต้องแปลงเป็นประเภทเดียวกันได้ มิฉะนั้น Compiler Error
- มี Return Type ขึ้นอยู่กับ Expression2/3
- ไม่ควรซ้อน Ternary Operator ลึกเกินไป (อ่านยาก)