Logical and Bitwise Operators in C++ tutorial

9/12/2025

Logical Bitwise Operars in cplus c++

Go Back

Logical and Bitwise Operators in 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  Bitwise Operars in cplus c++

Logical Operators

Logical operators are used to combine or invert boolean expressions.

OperatorDescriptionExampleResult
&&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

Bitwise operators perform operations on individual bits of integer data.

OperatorDescriptionExampleResult (if a=5, b=3)
& (AND)Sets each bit to 1 if both bits are 1a & b1 (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 1a ^ b6 (0101 ^ 0011 = 0110)
~ (NOT)Inverts all bits~a-6 (2's complement)
<< (Left Shift)Shifts bits left, fills with 0a << 110 (0101 << 1 = 1010)
>> (Right Shift)Shifts bits righta >> 12 (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

Summary

  • 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.

Table of content