Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C++ Operators

Operators do the work on values: arithmetic, comparisons and combining conditions. They are the same as in C, so if you know C you can skim this page.

Arithmetic

#include <iostream>

int main() {
    int a = 17, b = 5;
    std::cout << "a + b = " << a + b << "\n";
    std::cout << "a - b = " << a - b << "\n";
    std::cout << "a * b = " << a * b << "\n";
    std::cout << "a / b = " << a / b << "\n";
    std::cout << "a % b = " << a % b << "\n";
    std::cout << "a / 5.0 = " << a / 5.0 << "\n";
    return 0;
}
Output
a + b = 22
a - b = 12
a * b = 85
a / b = 3
a % b = 2
a / 5.0 = 3.4

When both numbers are integers, / is integer division and drops the fraction: 17 / 5 is 3. Make one side a decimal, or use static_cast<double>(a) / b, to get 3.4. % gives the remainder of an integer division; n % 2 == 0 tests for an even number. Never divide an integer by zero: the result is undefined (our editor stops the program with a message).

Assignment, increment and decrement

x += 3 means x = x + 3; the same works for -=, *=, /= and %=. x++ adds 1 and x-- subtracts 1.

#include <iostream>

int main() {
    int x = 10;
    x += 5;
    x *= 2;
    x++;
    std::cout << "x = " << x << "\n";
    return 0;
}
Output
x = 31

Comparison and logical operators

Comparisons (==, !=, <, >, <=, >=) give a bool. && (and), || (or) and ! (not) combine them. std::boolalpha makes cout print true and false instead of 1 and 0.

#include <iostream>

int main() {
    int age = 15;
    std::cout << std::boolalpha;
    std::cout << "teenager: " << (age >= 13 && age <= 19) << "\n";
    std::cout << "adult: " << (age >= 18) << "\n";
    std::cout << "not adult: " << !(age >= 18) << "\n";
    return 0;
}
Output
teenager: true
adult: false
not adult: true

Put brackets around a comparison inside a cout statement: << binds more tightly than < or ==, so std::cout << a < b does not do what it looks like.

Precedence

*, / and % come before + and -; comparisons after arithmetic; && before ||; assignment last. Use brackets whenever the order is not obvious; they also tell the reader what you meant.

Practice exercises

  1. Convert 135 minutes into hours and minutes with / and %.
  2. Print whether a number is even, as true or false.
  3. Compute the average of three integers with decimals.