C++ Operators
C++ operators perform calculations, comparisons and logic on values. Most are the same as in C, and C++20 adds the three-way comparison operator <=>.
Arithmetic and Assignment
#include <iostream>
int main() {
int a = 20, b = 6;
std::cout << a + b << ' ' << a - b << ' ' << a * b << '\n';
std::cout << a / b << ' ' << a % b << '\n'; // integer division
std::cout << static_cast<double>(a) / b << '\n';
a += 4;
std::cout << a << '\n';
}26 14 120 3 2 3.33333 24
Comparison and Logical Operators
Comparisons produce bool values. Use && (and), || (or) and ! (not) to combine them. C++ also accepts the words and, or and not.
#include <iostream>
int main() {
int age = 16;
bool withParent = true;
std::cout << std::boolalpha;
std::cout << (age >= 18) << '\n';
std::cout << (age >= 18 || withParent) << '\n';
}false true
Increment and Decrement
++x increments then returns the new value; x++ returns the old value then increments.
#include <iostream>
int main() {
int x = 5;
int a = x++;
int b = ++x;
std::cout << a << ' ' << b << ' ' << x << '\n';
}5 7 7
Operator Tips
- Use static_cast<double>(x) instead of C-style casts.
- Parentheses make precedence obvious.
- = assigns and == compares; compiler warnings help catch mistakes.
- The C++20 <=> operator compares two values in one step and lets classes get all comparison operators automatically.
Frequently asked questions
Why does 7 / 2 give 3 in C++?
Both operands are integers, so C++ uses integer division and discards the remainder. Use 7.0 / 2 or static_cast<double> to get 3.5.
What is the spaceship operator in C++?
The <=> operator, added in C++20, returns whether one value is less than, equal to or greater than another. Defaulting it in a class generates all comparison operators.
What is static_cast in C++?
static_cast is the safe, explicit way to convert between related types such as int and double. It is easier to search for and stricter than a C-style cast.