Logical and Bitwise Operators in C++ tutorial
Logical Bitwise Operars in cplus c++
Introduction
Logical operators are used for boolean logic in conditions, while bitwise operators work at the bit level to manipulate individual bits of data.
Logical operators are used to combine or invert boolean expressions.
| Operator | Description | Example | Result |
|---|---|---|---|
&& |
Logical AND (true if both are true) |
(x > 0 && y > 0) |
true/false |
| ` | ` | Logical OR (true if at least one is true) | |
! |
Logical NOT (inverts boolean value) |
!(x > 0) |
true/false |
Example:
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10;
cout << (a > 0 && b > 0) << endl; // 1
cout << (a > 0 || b < 0) << endl; // 1
cout << !(a > b) << endl; // 1
return 0;
}
Output:
1
1
1
Bitwise operators perform operations on individual bits of integer data.
| Operator | Description | Example | Result (if a=5, b=3) |
|---|---|---|---|
& (AND) |
Sets each bit to 1 if both bits are 1 |
a & b |
1 (0101 & 0011 = 0001) |
| ` | ` (OR) | Sets each bit to 1 if one of the bits is 1 | `a |
^ (XOR) |
Sets each bit to 1 if only one is 1 |
a ^ b |
6 (0101 ^ 0011 = 0110) |
~ (NOT) |
Inverts all bits |
~a |
-6 (2's complement) |
<< (Left Shift) |
Shifts bits left, fills with 0 |
a << 1 |
10 (0101 << 1 = 1010) |
>> (Right Shift) |
Shifts bits right |
a >> 1 |
2 (0101 >> 1 = 0010) |
Example:
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 3;
cout << (a & b) << endl; // 1
cout << (a | b) << endl; // 7
cout << (a ^ b) << endl; // 6
cout << (~a) << endl; // -6
cout << (a << 1) << endl; // 10
cout << (a >> 1) << endl; // 2
return 0;
}
Output:
1
7
6
-6
10
2
Logical operators work on boolean values and are commonly used in conditions.
Bitwise operators manipulate bits and are useful in low-level programming and optimization.
Mastering these operators is important for writing efficient C++ code.