Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Conditional Ternary Operator (?:) ใน C++


นิยาม

Conditional operator ? : เป็น ternary operator (รับ 3 operands) ทำงานดังนี้:

  1. Operand แรกแปลงเป็น bool ประเมินค่าและทำ side effects เสร็จก่อน
  2. ถ้า operand แรกเป็น true (1) -> ประเมิน operand ที่สอง
  3. ถ้า operand แรกเป็น false (0) -> ประเมิน operand ที่สาม

ผลลัพธ์คือค่าของ operand ที่ถูกประเมิน (ตัวที่สองหรือตัวที่สาม) มีเพียงหนึ่งเดียวที่ถูกประเมิน 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 type -> ใช้ภาษากฎกำหนด 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.