C++ Tutorial · C++ Basics · Lesson 6 of 21
C++ Operators and Math
Arithmetic, comparison, logical operators and <cmath>.
Operators
Arithmetic + - * / %, increment ++ --, comparison == != < > <= >=, logical && || !, and C++20's three-way comparison <=>. Integer division truncates.
#include <algorithm>
#include <cmath>
#include <iostream>
int main() {
int a = 17, b = 5;
std::cout << a + b << ' ' << a - b << ' ' << a * b << ' ' << a / b << ' ' << a % b << '\n';
std::cout << std::boolalpha << (a > b && b > 0) << '\n';
std::cout << std::sqrt(144.0) << ' ' << std::pow(2, 10) << ' ' << std::abs(-7) << '\n';
std::cout << std::round(2.5) << ' ' << std::floor(2.7) << ' ' << std::ceil(2.1) << '\n';
std::cout << std::max(4, 9) << ' ' << std::min({4, 9, 1}) << '\n';
}
Output
22 12 85 3 2 true 12 1024 7 3 2 3 9 1
Run this on your computer — see “Get Started” for setup.
Watch out for integer overflow — overflowing a signed int is undefined behaviour. Use a wider type when values can be large.
Test yourself
What is 7 / 2 for ints in C++?
33.54Undefined
Show answer
Answer: 3