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

ความแตกต่างระหว่าง Bitwise AND และ Logical AND ใน C/C++

Bitwise AND = & Logical AND = && ความแตกต่างพื้นฐาน:

  • Logical AND (&&) ทำงานกับ Boolean expression คืนค่า Boolean (true/false) เท่านั้น
  • Bitwise AND (&) ทำงานกับ integer, short, long, unsigned int คืนค่าชนิดเดียวกับอ็อปแรนด์

ตัวอย่าง

#include <iostream>
using namespace std;

int main() {
    int x = 3;  // 0011
    int y = 7;  // 0111
    if (y > 1 && y > x)
        cout << "y is greater than 1 AND x" << endl;
    int z = x & y;  // 0011 = 3
    cout << "z = " << z;
}

เอาต์พุต

y is greater than 1 AND x
z = 3
  • Short-circuit evaluation: && ไม่ประเมิน operand ตัวที่ 2 ถ้าตัวแรกเป็น false || ไม่ประเมินตัวที่ 2 ถ้าตัวแรกเป็น true แต่ & และ | ประเมินทั้งคู่เสมอ

ตัวอย่าง

#include <iostream>
using namespace std;

int main() {
    int x = 0;
    cout << (x && printf("Test using && ")) << endl;
    cout << (x & printf("Test using & "));
}

เอาต์พุต

0
Test using & 0

ใน && ไม่พิมพ์ "Test using &&" เพราะ x=0 (false) จบการประเมินทันที แต่ & ประเมินทั้งคู่ จึงพิมพ์ "Test using &"