Assignment Operators
Lesson outline
Introduction to Assignment Operators
Assignment operators in C++ are used to set or update the value of variables. The most basic is =, which assigns the value on the right-hand side to the variable on the left-hand side.
C++ also provides compound assignment operators that combine an operation (like addition or multiplication) with assignment, making code shorter and clearer.
Basic Assignment Operator
The = operator stores the value on its right into the variable on its left.
Compound Assignment Operators
| Operator | Example | Equivalent To |
|---|---|---|
| += | x += 3 | x = x + 3 |
| -= | x -= 3 | x = x - 3 |
| *= | x *= 3 | x = x * 3 |
| /= | x /= 3 | x = x / 3 |
| %= | x %= 3 | x = x % 3 |
Multiple Assignments
C++ allows chaining of assignment operations, so several variables can be given the same value in one statement.
Other Compound Assignment Operators (Bitwise & Shifts)
C++ also provides bitwise and shift compound assignments:
| Operator | Example | Equivalent To |
|---|---|---|
| &= | x &= y | x = x & y |
| |= | x |= y | x = x | y |
| ^= | x ^= y | x = x ^ y |
| <<= | x <<= k | x = x << k |
| >>= | x >>= k | x = x >> k |
Best Practices
- Prefer compound assignment operators to make code concise and expressive.
- Avoid writing assignments inside complex expressions where side effects may reduce readability or cause logic errors.
- Initialize variables at the point of declaration whenever possible.
- Use parentheses to make the order of operations explicit; assignment has lower precedence than arithmetic/bitwise operators.
- Don't confuse
=(assignment) with==(equality) in conditions; consider writingif (expected == x)to avoid accidental assignments. - You cannot assign to
constobjects, and references cannot be rebound by assignment (assignment changes the referred-to object, not the binding).
Type Conversions & Safety Notes
Compound assignments apply the usual arithmetic conversions to bring operands to a common type; this can truncate when assigning back to a narrower type.
For integer division with /= the result truncates toward zero; %= yields a remainder with the same sign as the left operand.
Division or modulo by zero is undefined behavior (for integers).