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

Equality Operators (== และ !=) ใน C++


บทนำ

Equality operators ใน C++ คือ == (equal to) และ != (not equal to) ทำงานตามชื่อของมัน Operator เหล่านี้เปรียบเทียบ operands สำหรับความเท่าหรือไม่เท่าแบบเคร่งครัด

Precedence ต่ำกว่า relational operators แต่พฤติกรรมคล้ายกัน ผลลัพธ์เป็นชนิด bool

  • == คืน true (1) ถ้าทั้งสอง operand มีค่าเท่ากัน มิฉะนั้น false (0)
  • != คืน true ถ้า operand ไม่เท่ากัน มิฉะนั้น false

ตัวอย่าง

#include <iostream>
using namespace std;

int main() {
    cout << boolalpha  // แสดง true/false แทน 1/0
         << "The true expression 3 != 2 yields: "
         << (3 != 2) << endl
         << "The false expression 20 == 10 yields: "
         << (20 == 10) << endl;
}

ผลลัพธ์

The true expression 3 != 2 yields: true
The false expression 20 == 10 yields: false