C++ Assignment Operators
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=
)
to assign the value 10 to a variable called x:
The addition compound assignment operator (+=
) adds a value to a variable:
A list of all assignment operators:
Operator | Example | Same As | Try it |
---|---|---|---|
= | x = 5 | x = 5 | Try it » |
+= | x += 3 | x = x + 3 | Try it » |
-= | x -= 3 | x = x - 3 | Try it » |
*= | x *= 3 | x = x * 3 | Try it » |
/= | x /= 3 | x = x / 3 | Try it » |
%= | x %= 3 | x = x % 3 | Try it » |
&= | x &= 3 | x = x & 3 | Try it » |
|= | x |= 3 | x = x | 3 | Try it » |
^= | x ^= 3 | x = x ^ 3 | Try it » |
>>= | x >>= 3 | x = x >> 3 | Try it » |
<<= | x <<= 3 | x = x << 3 | Try it » |
Compound Assignment Operators
Compound assignment operators are a shorter way of writing operations where you use a variable in both sides of an assignment.
For example, instead of writing x = x + 5;
, you can simply write x += 5;
.
Example
int x = 10;
x += 5; // same as x = x + 5
cout << x << "\n"; // 15
x *= 2; // same as x = x * 2
cout << x << "\n"; // 30
Try it Yourself »
Tip: Compound operators make code shorter and easier to read, especially when updating the same variable many times.
Why "Compound"?
They are called compound assignment operators because they combine a regular operator (like +
, -
, *
, etc.) with the assignment operator (=
) into one single operator.
For example, +=
is a combination of +
and =
.
Real-Life Example: Tracking Savings
Compound assignment operators can also be used in real-life scenarios.
For example, you can use the +=
operator to keep track of savings when you add money to an account:
Example
int savings = 100;
savings += 50; // add 50 to savings
cout << "Total savings: " << savings;
Try it Yourself »