In C++, assignment operators allow variables to store and update values efficiently. These operators assign values directly or perform operations before assignment.
Basic Assignment (=
)
The simplest assignment operator is =
, which stores a value in a variable.
Example
C++
x
using namespace std;
int main() {
int engineCC = 1000; // Assigning a value
cout << "Engine capacity: " << engineCC << " cc";
return 0;
}
Using Compound Assignment Operators
Assignment operators can modify variables while assigning a value.
Example
C++
using namespace std;
int main() {
int torque = 80; // Initial value
torque += 20; // Adds 20 to torque (80 + 20 = 100)
cout << "Updated torque: " << torque << " Nm";
return 0;
}
This shorthand makes the code cleaner, eliminating the need for torque = torque + 20;
.
Common Assignment Operators
Operator | Example | Equivalent Expression |
---|---|---|
= | power = 100; | power = 100; |
+= | power += 50; | power = power + 50; |
-= | power -= 30; | power = power - 30; |
*= | power *= 2; | power = power * 2; |
/= | power /= 4; | power = power / 4; |
%= | power %= 3; | power = power % 3; |
Bitwise Assignment Operators
Operator | Example | Equivalent Expression |
---|---|---|
&= | 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; |