Course Content
C++ Tutorial
About Lesson

Assignment Operators

Assignment operators are fundamental elements in C++ programming, used to assign values to variables. They offer concise ways to modify variables based on specific operations. Here’s a breakdown of the primary assignment operators:

The Basic Assignment Operator (=)

The basic assignment operator (=) is used to assign a value to a variable. For example:

int x = 10;

Compound Assignment Operators

Addition Assignment Operator (+=)

The addition assignment operator (+=) adds the value on the right-hand side to the variable on the left-hand side and assigns the result to the variable.

int x = 5;
x += 3; // This is equivalent to x = x + 3;
Subtraction Assignment Operator (-=)

The subtraction assignment operator (-=) subtracts the value on the right-hand side from the variable on the left-hand side and assigns the result to the variable.

int x = 10;
x -= 4; // This is equivalent to x = x - 4;
Multiplication Assignment Operator (*=)

The multiplication assignment operator (*=) multiplies the variable on the left-hand side by the value on the right-hand side and assigns the result to the variable.

int x = 3;
x *= 5; // This is equivalent to x = x * 5;
Division Assignment Operator (/=)

The division assignment operator (/=) divides the variable on the left-hand side by the value on the right-hand side and assigns the result to the variable.

float x = 12.0;
x /= 4; // This is equivalent to x = x / 4;

Miscellaneous Assignment Operators

Modulus Assignment Operator (%=)

The modulus assignment operator (%=) assigns the remainder of the division of the variable on the left-hand side by the value on the right-hand side to the variable.

int x = 10;
x %= 3; // This is equivalent to x = x % 3;
Bitwise Assignment Operators

C++ also provides bitwise assignment operators like &=, |=, ^=, <<=, and >>=. These operators perform bitwise AND, OR, XOR, left shift, and right shift operations, respectively, along with assignment.

Understanding these assignment operators in C++ is crucial for efficient and concise programming. They offer shortcuts to perform operations while assigning values to variables, enhancing code readability and efficiency