Assignment Operators
The assignment operator
= stores a value into a variable. C++
also provides **compound assignment operators** that combine an arithmetic or
bitwise operation with an assignment in a single, more concise step.
Basic Assignment
CPP
int score = 0; // this = is initialization, not assignment (see note below) score = 10; // this = is assignment — score already existed
Compound Assignment Operators
Operator | Equivalent To | Example |
|---|---|---|
+= | a = a + b | total += 10; |
-= | a = a - b | total -= 5; |
*= | a = a * b | price *= 1.1; |
/= | a = a / b | average /= count; |
%= | a = a % b | remainder %= 7; |
&= | a = a & b | flags &= mask; |
|= | a = a | b | flags |= FLAG_VISIBLE; |
^= | a = a ^ b | flags ^= FLAG_SELECTED; |
<<= | a = a << b | value <<= 2; |
= | a = a >> b | value >>= 1; |
CPP
#include <iostream>
int main() {
int total = 100;
total += 20; // total = 120
total -= 5; // total = 115
total *= 2; // total = 230
total /= 10; // total = 23
total %= 5; // total = 3
std::cout << total << std::endl;
return 0;
}Chained Assignment
Assignment is an expression that evaluates to the assigned value, and it associates right-to-left, so you can chain several assignments in one statement.
CPP
int a, b, c; a = b = c = 0; // evaluated right-to-left: c = 0, then b = (c's value), then a = (b's value) // all three variables are now 0
Assignment vs Initialization
These look the same but are different operations
In
int x = 5;, the = is initialization — it is giving the variable its very first value as part of its creation. In x = 10; (on a later line, where x already exists), the = is assignment — it replaces an existing value. The distinction matters because some types behave differently for each: a type can define a constructor for initialization and a separate operator= for assignment, and the rules for what is legal (e.g. with const or reference members) differ between the two.CPP
#include <string>
int main() {
std::string s1 = "hello"; // initialization — calls a constructor
std::string s2; // default-initialized (empty string)
s2 = "world"; // assignment — calls operator=
const int x = 5; // initialization — legal even though x is const
// x = 10; // ERROR: assignment to a const variable is illegal
return 0;
}