Variables store data, but a program becomes useful only when it does something with that data: adds marks, compares ages, checks whether a number is even, combines conditions. The symbols that perform these actions are called operators.
C++ inherits almost all of C's operators and adds a few of its own. In this chapter we will go through every operator group you need for exams, GATE and interviews, and we will spend extra time on the parts that cause real bugs: integer division, ++/--, short-circuit evaluation, precedence and undefined behavior.
What is an Operator?
An operator is a symbol that tells the compiler to perform a specific operation on one or more values, called operands, and produce a result.
In a + b, + is the operator and a, b are the operands. The whole thing is an expression, and every expression has a value and a type.
Operators are classified by the number of operands:
| Kind | Operands | Examples |
|---|---|---|
| Unary | 1 | -x, !flag, ++i, ~bits, sizeof x |
| Binary | 2 | a + b, a < b, a && b, a = b |
| Ternary | 3 | cond ? x : y (the only one) |
And by what they do:
| Group | Operators |
|---|---|
| Arithmetic | + - * / % |
| Increment / Decrement | ++ -- |
| Assignment | = += -= *= /= %= &= |= ^= <<= >>= |
| Relational (comparison) | == != < > <= >= <=> |
| Logical | && || ! |
| Bitwise | & | ^ ~ << >> |
| Conditional | ?: |
| Others | sizeof, comma ,, scope ::, member access . and ->, new/delete, casts |
1. Arithmetic Operators
#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'; // integer division
std::cout << "a % b = " << a % b << '\n'; // remainder
std::cout << "17.0 / 5 = " << 17.0 / 5 << '\n'; // floating-point division
std::cout << "-17 / 5 = " << -17 / 5 << '\n';
std::cout << "-17 % 5 = " << -17 % 5 << '\n';
std::cout << "17 % -5 = " << 17 % -5 << '\n';
return 0;
}
Output:
a + b = 22
a - b = 12
a * b = 85
a / b = 3
a % b = 2
17.0 / 5 = 3.4
-17 / 5 = -3
-17 % 5 = -2
17 % -5 = 2
Integer Division Throws Away the Fraction
When both operands are integers, / performs integer division: 17 / 5 is 3, not 3.4. The fractional part is simply discarded. If at least one operand is floating-point, as in 17.0 / 5, you get real division.
Since C++11 the rule is fixed: integer division truncates toward zero. So -17 / 5 is -3 (not -4, which would be rounding down).
The Sign of %
The % operator gives the remainder and works only on integers (use std::fmod from <cmath> for floating-point). The language guarantees this identity whenever a / b is representable:
(a / b) * b + (a % b) == a
Let's check -17 % 5: (-17 / 5) * 5 = -3 * 5 = -15, so the remainder must be -17 - (-15) = -2. A handy rule: the result of % has the same sign as the left operand (the dividend).
Division by Zero
Integer division or remainder by zero (x / 0, x % 0) is undefined behavior: the program may crash, print garbage, or seem to work. Always check the divisor first. (For floating-point types on typical IEEE-754 systems, 1.0 / 0.0 gives infinity instead.)
2. Increment and Decrement
++ adds 1 and -- subtracts 1. Each has two forms, and the difference is only in which value the expression produces.
| Form | Name | What happens | Value of the expression |
|---|---|---|---|
++x | Pre-increment | Increase x | The new value |
x++ | Post-increment | Increase x | The old value |
--x | Pre-decrement | Decrease x | The new value |
x-- | Post-decrement | Decrease x | The old value |
#include <iostream>
int main() {
int x = 5;
int y = ++x; // pre-increment: increase first, then use
std::cout << "x = " << x << ", y = " << y << '\n';
int p = 5;
int q = p++; // post-increment: use first, then increase
std::cout << "p = " << p << ", q = " << q << '\n';
int m = 10;
int n = m-- - 2; // uses 10, then m becomes 9
std::cout << "m = " << m << ", n = " << n << '\n';
return 0;
}
Output:
x = 6, y = 6
p = 6, q = 5
m = 9, n = 8
Step by step for int q = p++;:
p = 5
p++ → expression value is 5 (old value), p becomes 6
q = 5
A small C++-specific point: ++x gives back the variable itself (an lvalue), so ++(++x) is legal. x++ gives back a temporary copy of the old value, so (x++)++ does not compile. When the result is not used (for example in a loop counter), prefer ++i; for class types such as iterators it avoids making a copy.
3. Assignment Operators
= copies the value on the right into the variable on the left. The compound assignment operators combine an operation with assignment: x += 5 means x = x + 5, except that x is evaluated only once.
#include <iostream>
int main() {
int balance = 1000;
balance += 500; // balance = balance + 500
std::cout << balance << '\n';
balance -= 200;
std::cout << balance << '\n';
balance *= 2;
std::cout << balance << '\n';
balance /= 3;
std::cout << balance << '\n';
balance %= 100;
std::cout << balance << '\n';
int a, b, c;
a = b = c = 7; // assignment is right-associative
std::cout << a << ' ' << b << ' ' << c << '\n';
return 0;
}
Output:
1500
1300
2600
866
66
7 7 7
2600 / 3 is 866 because of integer division, and 866 % 100 is 66. The chain a = b = c = 7 works because assignment groups right to left: it is a = (b = (c = 7)), and an assignment expression produces the assigned variable.
4. Relational (Comparison) Operators
Relational operators compare two values and produce a bool: true or false.
#include <iostream>
#include <compare>
int main() {
int a = 10, b = 20;
std::cout << std::boolalpha;
std::cout << (a == b) << ' ' << (a != b) << ' ' << (a < b) << ' '
<< (a > b) << ' ' << (a <= 10) << ' ' << (b >= 25) << '\n';
auto r = a <=> b; // C++20 three-way comparison
std::cout << (r < 0) << ' ' << (r == 0) << ' ' << (r > 0) << '\n';
return 0;
}
Output:
false true true false true false
true false false
Note the parentheses around each comparison. They are needed because << has higher precedence than == and <. Without them, std::cout << a == b would mean (std::cout << a) == b, which does not compile.
The Spaceship Operator <=> (C++20)
a <=> b answers "less, equal or greater?" in a single comparison. The result is not a bool but an ordering object that you compare with 0: (r < 0) means a < b, (r == 0) means equal, (r > 0) means a > b. Its real power appears when defining comparisons for your own classes, covered in Operator Overloading.
5. Logical Operators
Logical operators combine conditions.
| A | B | A && B | A || B | !A |
|---|---|---|---|---|
| false | false | false | false | true |
| false | true | false | true | true |
| true | false | false | true | false |
| true | true | true | true | false |
Any number can be used as a condition: 0 means false and any non-zero value means true. C++ also accepts the keywords and, or and not as alternative spellings of &&, || and !, though most code uses the symbols.
Short-Circuit Evaluation
Short-circuit evaluation:
&&and||always evaluate the left operand first, and evaluate the right operand only if it is needed to decide the result.
- For
A && B: ifAis false, the result is already false, soBis not evaluated. - For
A || B: ifAis true, the result is already true, soBis not evaluated.
We can watch this happen with a small helper function that prints a message whenever it runs (functions are explained in the Functions chapter):
#include <iostream>
bool check(const char* name, bool value) {
std::cout << " evaluating " << name << '\n';
return value;
}
int main() {
std::cout << std::boolalpha;
std::cout << "AND:\n";
bool r1 = check("A", false) && check("B", true);
std::cout << " result = " << r1 << '\n';
std::cout << "OR:\n";
bool r2 = check("A", true) || check("B", false);
std::cout << " result = " << r2 << '\n';
std::cout << "NOT: " << !true << '\n';
int count = 0, total = 50;
// Safe: division happens only if count != 0
bool ok = (count != 0) && (total / count > 10);
std::cout << "ok = " << ok << '\n';
return 0;
}
Output:
AND:
evaluating A
result = false
OR:
evaluating A
result = true
NOT: false
ok = false
B was never evaluated in either case. The last example shows why this is useful: total / count would be a division by zero, but it never runs because count != 0 is false. This "guard first, then use" pattern is extremely common, for example ptr != nullptr && ptr->value > 0.
6. Bitwise Operators
Bitwise operators work on the individual bits of integers. They are heavily used in GATE questions, embedded programming, and competitive programming tricks.
| Operator | Name | Result bit is 1 when... |
|---|---|---|
& | AND | both bits are 1 |
| | OR | at least one bit is 1 |
^ | XOR | the bits are different |
~ | NOT (complement) | the bit was 0 (flips every bit) |
<< | Left shift | shifts bits left, filling with 0 |
>> | Right shift | shifts bits right |
Worked example with a = 12 and b = 10:
a = 1100 (12)
b = 1010 (10)
----------------
a & b = 1000 (8)
a | b = 1110 (14)
a ^ b = 0110 (6)
a << 2 = 110000 (48) = 12 × 2²
a >> 2 = 0011 (3) = 12 / 2²
#include <iostream>
#include <bitset>
int main() {
unsigned int a = 12; // 1100
unsigned int b = 10; // 1010
std::cout << "a & b = " << (a & b) << '\n'; // 1000 = 8
std::cout << "a | b = " << (a | b) << '\n'; // 1110 = 14
std::cout << "a ^ b = " << (a ^ b) << '\n'; // 0110 = 6
std::cout << "a << 2 = " << (a << 2) << '\n'; // 110000 = 48
std::cout << "a >> 2 = " << (a >> 2) << '\n'; // 11 = 3
std::cout << "~a = " << std::bitset<8>(~a) << " (last 8 bits)\n";
int n = 37;
std::cout << n << " is " << ((n & 1) ? "odd" : "even") << '\n';
std::cout << "bit 2 of 37 is " << ((n >> 2) & 1) << '\n'; // 37 = 100101
return 0;
}
Output:
a & b = 8
a | b = 14
a ^ b = 6
a << 2 = 48
a >> 2 = 3
~a = 11110011 (last 8 bits)
37 is odd
bit 2 of 37 is 1
std::bitset<8> (from <bitset>) is used only to display bits. Two classic tricks appear here: n & 1 is 1 for odd numbers and 0 for even ones, and (n >> k) & 1 extracts bit k.
Rules for Shifts
x << kmultiplies by 2k andx >> kdivides by 2k (rounding down) for non-negative values that don't overflow.- Shifting by a negative amount or by an amount ≥ the number of bits in the (promoted) type is undefined behavior. So for a 32-bit
int,1 << 32is UB. Use1LL << 40when you need a big power of two. - Since C++20, signed integers are defined to be two's complement:
>>on a negative number is an arithmetic shift (it keeps the sign, so-8 >> 1is-4), and<<on signed values is defined as wrapping modulo 2N. Before C++20, left-shifting a negative value was undefined and right-shifting one was implementation-defined. - Don't confuse
&/|(bitwise, always evaluate both sides) with&&/||(logical, short-circuit).
7. The Conditional (Ternary) Operator
condition ? value1 : value2 evaluates condition; if it is true, the result is value1, otherwise value2. Only one of the two values is evaluated.
#include <iostream>
int main() {
int marks = 72;
const char* result = (marks >= 40) ? "Pass" : "Fail";
std::cout << result << '\n';
int a = 8, b = 13;
int bigger = (a > b) ? a : b;
std::cout << "Bigger: " << bigger << '\n';
return 0;
}
Output:
Pass
Bigger: 13
The ternary operator is an expression, so it can be used where a value is needed, such as initialising a variable. We will compare it with if-else in Conditional Statements.
8. sizeof and the Comma Operator
sizeof gives the size in bytes of a type or an expression's type. It is evaluated at compile time; the expression inside is not executed. Its result has type std::size_t. The parentheses are required for a type (sizeof(int)) but optional for an expression (sizeof x).
The comma operator evaluates its left operand, discards the result, then evaluates the right operand, which becomes the value of the whole expression.
#include <iostream>
int main() {
int x = 10;
double d = 2.5;
std::cout << sizeof(int) << ' ' << sizeof(double) << ' ' << sizeof(char) << '\n';
std::cout << sizeof x << ' ' << sizeof(d * 2) << '\n';
int y = (x++, x + 100); // comma: evaluate x++, then x + 100
std::cout << "x = " << x << ", y = " << y << '\n';
return 0;
}
Output (on a typical 64-bit Linux or Windows system):
4 8 1
4 8
x = 11, y = 111
sizeof(char) is always 1 by definition. The other sizes depend on the platform, as discussed in Variables & Data Types. Not every comma is the comma operator: the commas in int a, b; and in function calls like f(a, b) are just separators.
Precedence and Associativity
Precedence decides which operator is applied first when different operators appear together. Associativity decides the grouping when operators of the same precedence appear together.
Here is a simplified table from highest to lowest precedence:
| Level | Operators | Associativity |
|---|---|---|
| 1 | :: | Left to right |
| 2 | a++ a--, function call (), [], ., -> | Left to right |
| 3 | ++a --a, unary + -, ! ~, C-style cast, *p, &x, sizeof, new, delete | Right to left |
| 4 | .* ->* | Left to right |
| 5 | * / % | Left to right |
| 6 | + - | Left to right |
| 7 | << >> | Left to right |
| 8 | <=> | Left to right |
| 9 | < <= > >= | Left to right |
| 10 | == != | Left to right |
| 11 | & | Left to right |
| 12 | ^ | Left to right |
| 13 | | | Left to right |
| 14 | && | Left to right |
| 15 | || | Left to right |
| 16 | ?:, = and all compound assignments, throw | Right to left |
| 17 | , | Left to right |
A useful memory aid: unary → arithmetic → shift → relational → equality → bitwise → logical → ternary/assignment → comma.
Worked Examples
#include <iostream>
int main() {
std::cout << 2 + 3 * 4 << '\n'; // * before +
std::cout << (2 + 3) * 4 << '\n';
std::cout << 20 / 4 * 5 << '\n'; // left to right: (20 / 4) * 5
std::cout << 2 + 3 * 4 % 5 - 1 << '\n';
std::cout << (10 - 4 - 3) << '\n'; // (10 - 4) - 3
return 0;
}
Output:
14
20
25
3
3
Let's evaluate 2 + 3 * 4 % 5 - 1 step by step. * and % have the same precedence and group left to right:
2 + 3 * 4 % 5 - 1
2 + (3 * 4) % 5 - 1 → 2 + 12 % 5 - 1
2 + (12 % 5) - 1 → 2 + 2 - 1
(2 + 2) - 1 → 3
Precedence Traps
#include <iostream>
int main() {
int x = 6;
std::cout << std::boolalpha;
std::cout << (x & 1 == 0) << '\n'; // intended: is x even?
std::cout << ((x & 1) == 0) << '\n'; // correct
int a = 5, b = 3, c = 2;
std::cout << (a > b > c) << '\n'; // intended: 5 > 3 > 2
std::cout << (a > b && b > c) << '\n'; // correct
return 0;
}
Output:
0
true
false
true
Why are the first and third lines wrong?
==has higher precedence than&, sox & 1 == 0meansx & (1 == 0)=6 & false=6 & 0=0. It prints0(anint, notfalse).a > b > cmeans(5 > 3) > 2=true > 2=1 > 2=false. Chained comparisons do not work like in mathematics.
With -Wall, GCC warns about both lines (“suggest parentheses around comparison in operand of ‘&’” and “comparisons like ‘X<=Y<=Z’ do not have their mathematical meaning”). When in doubt, add parentheses.
Order of Evaluation and Undefined Behavior
Precedence tells us how an expression is grouped, not the order in which the operands are computed. In f() + g(), C++ does not say whether f or g runs first. Only a few operators guarantee left-to-right evaluation: &&, ||, the comma operator, ?: (condition first), and since C++17 also <<, >>, [] and assignment (right side before left side).
The important rule: if one expression modifies a variable and also uses or modifies it again without the two being sequenced, the behavior is undefined.
#include <iostream>
int main() {
int i = 1;
int n = i++ + i++; // undefined behavior: i modified twice, unsequenced
std::cout << n << '\n';
return 0;
}
GCC warns:
warning: operation on ‘i’ may be undefined [-Wsequence-point]
There is no "correct" output for this program. Different compilers, or the same compiler with different optimisation levels, may print different values. The same applies to ++i + i and i = i++ + ++i. Some expressions that were UB in older C++ became well-defined in C++17 (for example i = i++ + 1 and std::cout << i << i++), but the simple rule is: don't modify a variable more than once in one expression, and don't read it in the same expression where you modify it. If an exam question asks for the output of i++ + i++, the correct answer is "undefined behavior".
Integer Overflow
Overflowing a signed integer is undefined behavior. Overflowing an unsigned integer is well-defined: it wraps around modulo 2N.
#include <iostream>
#include <climits>
int main() {
unsigned int u = UINT_MAX;
std::cout << "UINT_MAX + 1 = " << u + 1 << '\n'; // well-defined: wraps to 0
int big = INT_MAX;
std::cout << "INT_MAX = " << big << '\n';
int next = big + 1; // undefined behavior!
std::cout << "INT_MAX + 1 = " << next << '\n';
return 0;
}
Output with GCC 15 on x86-64:
UINT_MAX + 1 = 0
INT_MAX = 2147483647
INT_MAX + 1 = -2147483648
The last line looks like a clean wrap-around, but that is luck, not a guarantee. The optimiser is allowed to assume signed overflow never happens, which can silently break loops and checks. Compiling with -fsanitize=undefined catches it at run time with a message like this:
runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
When numbers can get large (sums of many values, products, factorials), use long long.
Common Mistakes
1. Using = Instead of ==
if (x = 5) assigns 5 to x and is always true. GCC warns with -Wall (-Wparentheses). We will see this again in Conditional Statements.
2. Expecting a Decimal Result From Integer Division
double avg = sum / count; with two ints does integer division first, then converts. Write static_cast<double>(sum) / count (see Type Conversion & Casting).
3. Forgetting Parentheses with <<
std::cout << a & b; means (std::cout << a) & b and does not compile. Write std::cout << (a & b);.
4. Using ^ for Power
2 ^ 3 is XOR, which equals 1, not 8. Use std::pow from <cmath> or 1 << k for powers of two.
5. Writing a < b < c
Write a < b && b < c.
6. Modifying a Variable Twice in One Expression
i++ + i++ is undefined behavior. Split it into separate statements.
Interview / GATE Questions
What is the value of -7 / 2 and -7 % 2 in C++?
-3 and -1. Integer division truncates toward zero (guaranteed since C++11), and (-7 / 2) * 2 + (-7 % 2) must equal -7, so the remainder is -1.
int x = 5; int y = x++ * 2 + ++x; Is this well-defined?
No. x is modified twice (x++ and ++x) in one expression, and the operands of * and + are unsequenced relative to each other, so the behavior is undefined.
What does int a = 0, b = 5; bool r = a && (b = 10); leave in b?
5. Because a is 0 (false), && short-circuits and (b = 10) is never evaluated.
What does 5 ^ 3 evaluate to?
6. In binary, 101 ^ 011 = 110. ^ is XOR, not exponentiation.
How can you check if a positive integer n is a power of two using bitwise operators?
(n & (n - 1)) == 0. A power of two has exactly one 1-bit; subtracting 1 turns that bit off and all lower bits on, so the AND is zero. For n = 8: 1000 & 0111 = 0000.
Is sizeof(x++) going to increment x?
No. The operand of sizeof is not evaluated (for ordinary types); only its type is used. x stays unchanged.
Why is 1 << 32 wrong when int is 32 bits, and how do you fix it?
Shifting by an amount greater than or equal to the width of the (promoted) left operand is undefined behavior. The literal 1 is an int, so the shift count 32 is too large. Make the left operand 64-bit: 1LL << 32 (or 1ULL << 32).
In Simple Words
Operators turn values into new values. Know integer division, the difference between
++xandx++, short-circuiting, and when to add parentheses.
17 / 5 = 3, 17 % 5 = 2 → integer division truncates toward zero
x++ → old value, ++x → new value
&&, || → short-circuit (right side may never run)
&, |, ^, ~, <<, >> → work on bits
signed overflow, x / 0, i++ + i++ → undefined behavior
when in doubt → add parentheses
We have seen that mixing types like int and double changes how operators behave. In the next chapter, Type Conversion & Casting, we will see exactly what conversions C++ performs and how to control them.