C++ Assignment Operators

In C++, assignment operators allow variables to store and update values efficiently. These operators assign values directly or perform operations before assignment.

Tutorials dojo strip



Basic Assignment (=)

The simplest assignment operator is =, which stores a value in a variable.

Example

C++




Using Compound Assignment Operators

Assignment operators can modify variables while assigning a value.

Example

C++

This shorthand makes the code cleaner, eliminating the need for torque = torque + 20;.




Common Assignment Operators

OperatorExampleEquivalent 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

OperatorExampleEquivalent 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;

Tutorials dojo strip