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

Logical Operators ใน C++


Logical Operators 3 ตัว

  • Logical OR (||)
  • Logical AND (&&)
  • Logical NOT (!)

Logical OR (||)

  • True ถ้า operand ไหนก็ตามเป็น true
  • Short-circuit: operand ที่ 2 ประเมินเฉพาะ operand แรกเป็น false
  • Left-to-right associativity
  • Operands: integral/pointer type (มักเป็น relational/equality expressions)

Logical AND (&&)

  • True ถ้าทั้งสอง operand เป็น true
  • Short-circuit: operand ที่ 2 ประเมินเฉพาะ operand แรกเป็น true
  • Left-to-right associativity

Logical NOT (!)

  • กลับความหมาย operand
  • Operand: arithmetic/pointer type → แปลงเป็น bool
  • False → True, True → False

ตัวอย่าง

#include <iostream>
using namespace std;

int main() {
    bool x = true, y = false;
    cout << (x || y) << endl;  // 1 (true)
    cout << (x && y) << endl;  // 0 (false)
    cout << (!x) << endl;       // 0 (false)
    return 0;
}

ผลลัพธ์

1
0
0

x=true, y=false: OR=true, AND=false, NOT x=false