What are the differences between bitwise and logical AND operators in C/C++


As we know the bit-wise AND is represented as ‘&’ and the logical operator is represented as ‘&&’. There are some fundamental differences between them. These are as follows −

  • The logical AND operator works on Boolean expressions, and returns Boolean values only. The bitwise AND operator works on integer, short int, long, unsigned int type data, and also returns that type of data.

Example

 Live Demo

#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
   cout << "z = "<< z;
}

Output

y is greater than 1 AND x
z = 3
  • The && operator does not evaluate second operand if first operand becomes false. Similarly, || operator does not evaluate second operand when first one becomes true, but bitwise operators like & and | always evaluate their operands.

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   int x = 0;
   cout << (x && printf("Test using && ")) << endl;
   cout << (x & printf("Test using & "));
}

Output

0
Test using & 0

Updated on: 17-Dec-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements