C++ Assignment Operators
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.
#include <iostream>
using namespace std;
int main() {
int x;
x = 5; // Assigns 5 to x
cout << x;
return 0;
}
5
Compound Assignment Operators
#include <iostream>
using namespace std;
int main() {
int total = 10;
total += 5; // total becomes 15
total *= 2; // total becomes 30
cout << total;
return 0;
}
30
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.
#include <iostream>
using namespace std;
int main() {
int a, b, c;
a = b = c = 5; // All variables get value 5
cout << a << " " << b << " " << c;
return 0;
}
5 5 5
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 writing `if (expected == x)` to avoid accidental assignments.
- You cannot assign to `const` objects, 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).