C++ Operators
Operators let you calculate, compare and combine values in C++.
Arithmetic Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 9 + 2 | 11 |
- | Subtract | 9 - 2 | 7 |
* | Multiply | 9 * 2 | 18 |
/ | Divide | 9 / 2 | 4 |
% | Remainder | 9 % 2 | 1 |
++ | Increase by 1 | x++ | |
-- | Decrease by 1 | x-- |
Example
cpp
#include <iostream>
using namespace std;
int main() {
int seconds = 200;
cout << seconds / 60 << " minutes and " << seconds % 60 << " seconds\n";
cout << 9 / 2.0 << "\n";
return 0;
}Output
3 minutes and 20 seconds 4.5
If both numbers are integers, / gives an integer. Write one as a decimal (2.0) or use static_cast<double> when you need the exact answer.
Prefix and Postfix
x++ uses the value first and then adds 1. ++x adds 1 first and then uses the value:
Example
cpp
#include <iostream>
using namespace std;
int main() {
int a = 5;
int b = a++; // b gets 5, then a becomes 6
int c = ++a; // a becomes 7, then c gets 7
cout << a << " " << b << " " << c << "\n";
return 0;
}Output
7 5 7
Assignment Operators
| Operator | Same as |
|---|---|
x += 4 | x = x + 4 |
x -= 4 | x = x - 4 |
x *= 4 | x = x * 4 |
x /= 4 | x = x / 4 |
x %= 4 | x = x % 4 |
Comparison Operators
Each comparison gives a bool result:
| Operator | Meaning |
|---|---|
== | Equal |
!= | Not equal |
>, < | Greater, less |
>=, <= | Greater or equal, less or equal |
Logical Operators
&&and: both must be true||or: at least one must be true!not: reverses true and false
Example
cpp
#include <iostream>
using namespace std;
int main() {
int marks = 72;
int attendance = 85;
bool eligible = marks >= 50 && attendance >= 75;
cout << boolalpha;
cout << "Eligible for exam: " << eligible << "\n";
cout << "Needs help: " << (marks < 40 || attendance < 60) << "\n";
return 0;
}Output
Eligible for exam: true Needs help: false
Order of Operations
*, / and % are done before + and -. Comparisons come after maths, and && comes before ||. When in doubt, use brackets:
Example
cpp
int x = 10 + 2 * 5; // 20
int y = (10 + 2) * 5; // 60Exercise
Exercise
What is printed by: int n = 3; cout << n++; ?
