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;
}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;
}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;
}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
- Convert 135 minutes into hours and minutes with
/and%. - Print whether a number is even, as
trueorfalse. - Compute the average of three integers with decimals.