C++ Operators

Operators work on values and variables.

Arithmetic operators

#include <iostream>

int main() {
    int a = 10, b = 3;
    std::cout << a + b << ' ' << a - b << ' ' << a * b << '\n';
    std::cout << a / b << ' ' << a % b << '\n';          // integer division and remainder
    std::cout << 10.0 / 3 << '\n';                         // decimal division
}
Output

13 7 30
3 1
3.33333

Assignment, increment and decrement

#include <iostream>

int main() {
    int x = 10;
    x += 5;  std::cout << x << ' ';
    x -= 3;  std::cout << x << ' ';
    x *= 2;  std::cout << x << ' ';
    x /= 4;  std::cout << x << ' ';
    x %= 4;  std::cout << x << '\n';

    int y = 5;
    std::cout << y++ << '\n';       // postfix: gives 5, then y is 6
    std::cout << y << '\n';
    std::cout << ++y << '\n';       // prefix: y becomes 7, then gives 7
    std::cout << --y << '\n';
}
Output

15 12 24 6 2
5
6
7
6

Comparison and logical operators

OperatorMeaning
== !=Equal, not equal
< > <= >=Compare sizes
<=>Three way comparison, the “spaceship” (C++20)
&&AND (short circuit)
||OR (short circuit)
!NOT
#include <compare>
#include <iostream>

int main() {
    int age = 25;
    bool has_id = true;
    std::cout << std::boolalpha;                       // print true/false, not 1/0
    std::cout << (age >= 18 && has_id) << ' ' << (age < 18 || has_id) << ' ' << !has_id << '\n';

    auto result = 3 <=> 5;
    std::cout << (result < 0) << '\n';                 // 3 is less than 5
}
Output

true true false
true

Ternary operator

#include <iostream>

int main() {
    int marks = 55;
    std::cout << (marks >= 40 ? "Pass" : "Fail") << '\n';
}
Output

Pass

Bitwise operators

#include <bitset>
#include <iostream>

int main() {
    unsigned a = 6, b = 3;                              // 110 and 011
    std::cout << (a & b) << ' ' << (a | b) << ' ' << (a ^ b) << ' ' << (a << 1) << ' ' << (a >> 1) << '\n';
    std::cout << std::bitset<8>(a) << ' ' << std::bitset<8>(~a) << '\n';
}
Output

2 7 5 12 3
00000110 11111001

Precedence

#include <iostream>

int main() {
    std::cout << 2 + 3 * 4 << ' ' << (2 + 3) * 4 << '\n';
}
Output

14 20

A warning: = is not ==

#include <iostream>

int main() {
    int x = 3;
    if (x = 5) {                    // assignment inside if: the compiler warns
        std::cout << "five\n";
    }
}
Output

Warn.cpp: In function 'int main()':
Warn.cpp:5:11: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
5 | if (x = 5) { // assignment inside if: the compiler warns
| ~~^~~

Note: Use brackets when you are not sure about the order of operators. Next: C++ Strings.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.