C++ Assignment operators

To give a variable a value in C++, use the assignment operators. There are different types of assignment operators available in C++, such as basic assignment operators, addition assignment operators, subtraction assignment operators, multiplication assignment operators, division assignment operators, and modulus assignment operators.

Here are the assignment operators in C++, along with their shorthand notation:

Operator
Description
Example
=
Simple assignment
x = 5;
+=
Addition assignment
x += 3; (x = x + 3;)
-=
Subtraction assignment
x -= 2; (x = x - 2;)
*=
Multiplication assignment
x *= 4; (x = x * 4;)
/=
Division assignment
x /= 2; (x = x / 2;)
%=
Modulus assignment
x %= 3; (x = x % 3;)
<<=
Left shift assignment
x <<= 2; (x = x << 2;)
>>=
Right shift assignment
x >>= 1; (x = x >> 1;)
&=
Bitwise AND assignment
x &= 7; (x = x & 7;)
^=
Bitwise XOR assignment
x ^= 1; (x = x ^ 1;)
|=
Bitwise OR assignment
x |= 2; (x = x | 2;)

The simple assignment operator assigns the value of the right-hand operand to the left-hand operand.

Example:

int x = 10;
int y = 20;
x = y;  // assigns the value of y to x

The addition assignment operator adds the value of the right-hand operand to the left-hand operand and assigns the result to the left-hand operand.

Example:

int x = 10;
int y = 20;
x += y;  // equivalent to x = x + y

The subtraction assignment operator subtracts the value of the right-hand operand from the left-hand operand and assigns the result to the left-hand operand.

Example:

int x = 10;
int y = 20;
x -= y;  // equivalent to x = x - y

The multiplication assignment operator multiplies the value of the right-hand operand with the left-hand operand and assigns the result to the left-hand operand.

Example:

int x = 10;
int y = 20;
x *= y;  // equivalent to x = x * y

The division assignment operator divides the value of the left-hand operand by the value of the right-hand operand and assigns the result to the left-hand operand.

Example:

int x = 10;
int y = 20;
x /= y;  // equivalent to x = x / y

The modulus assignment operator divides the value of the left-hand operand by the value of the right-hand operand and assigns the remainder to the left-hand operand.

Example:

int x = 10;
int y = 3;
x %= y;  // equivalent to x = x % y

Assignment operators in C++ are used to give a variable a value. Simple assignment operators, addition, subtraction, multiplication, division, and modulus assignment operators are just a few of the different types of assignment operators that are available in C++.