Skip to content

Latest commit

 

History

History
74 lines (48 loc) · 1.93 KB

File metadata and controls

74 lines (48 loc) · 1.93 KB

C++ Assignment Operators

Assignment operators are used to assign values to variables. In C++, apart from the basic assignment operator (=), there are several compound assignment operators that combine arithmetic operations with assignment.

List of Assignment Operators

  • = : Assign
  • += : Add and assign
  • -= : Subtract and assign
  • *= : Multiply and assign
  • /= : Divide and assign
  • %= : Modulus and assign

Usage and Examples

1. Assign (=)

The = operator assigns the value on its right to the variable on its left.

int a;
a = 5; // a is now 5

2. Add and Assign (+=)

The += operator adds the value on its right to the variable on its left and then assigns the result to the variable on the left.

int a = 5;
a += 3; // a is now 8

3. Subtract and Assign (-=)

The -= operator subtracts the value on its right from the variable on its left and then assigns the result to the variable on the left.

int a = 5;
a -= 3; // a is now 2

4. Multiply and Assign (*=)

The *= operator multiplies the variable on its left by the value on its right and then assigns the result to the variable on the left.

int a = 5;
a *= 3; // a is now 15

5. Divide and Assign (/=)

The /= operator divides the variable on its left by the value on its right and then assigns the result to the variable on the left.

int a = 15;
a /= 3; // a is now 5

6. Modulus and Assign (%=)

The %= operator calculates the modulus of the variable on its left by the value on its right and then assigns the result to the variable on the left.

int a = 15;
a %= 4; // a is now 3

Conclusion

Assignment operators in C++ simplify code by combining arithmetic operations with assignment. They are a shorthand way of performing operations and then storing the result in the same variable. Practice using these operators to become more familiar with their functionality.