นิยาม
Conditional operator ? : เป็น ternary operator (3 operands)
การทำงาน
- Operand แรกแปลงเป็น bool ประเมินเสร็จก่อน
- True → ประเมิน operand ที่ 2
- False → ประเมิน operand ที่ 3
ผลลัพธ์ = ค่าของ operand ที่ประเมิน (ตัวที่ 2 หรือ 3) มีเพียงหนึ่งตัวที่ถูกประเมิน Associativity: right-to-left
กฎชนิดข้อมูล Operand ที่ 2 และ 3
- ชนิดเดียวกัน → ผลลัพธ์เป็นชนิดนั้น
- Arithmetic/enumeration ทั้งคู่ → usual arithmetic conversions
- Pointer ทั้งคู่ หรือหนึ่ง pointer หนึ่งเป็น 0 → pointer conversions
- Reference ทั้งคู่ → reference conversions
- void ทั้งคู่ → void
- User-defined type เดียวกัน → ชนิดนั้น
- ชนิดต่างกันมี user-defined → ภาษากำหนด common type
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int i = 1, j = 2;
cout << (i > j ? i : j) << " is greater." << endl;
}
ผลลัพธ์
2 is greater.
หมายเหตุ: เนื้อหานี้ซ้ำกับ ID 1004083490