Assignment Operators in C++
Assignment operators in C++ are used to assign values to variables. These operators store a value in a variable and can also perform operations like addition, subtraction, multiplication, etc., while assigning.
Types of Assignment Operators
C++ provides the following assignment operators:
| Operator | Name | Meaning | Example |
|---|---|---|---|
= |
Simple Assignment | Assigns right-hand value to left-hand variable | x = 10 |
+= |
Add and Assign | Adds right value to variable and stores result | x += 5 |
-= |
Subtract and Assign | Subtracts right value and stores result | x -= 3 |
*= |
Multiply and Assign | Multiplies variable and stores result | x *= 2 |
/= |
Divide and Assign | Divides variable and stores result | x /= 4 |
%= |
Modulo and Assign | Finds remainder and stores result | x %= 3 |
Example Program
#include <iostream>
using namespace std;
int main()
{
int a = 10;
a += 5;
cout << "Value of a after += 5 : " << a << endl;
a -= 3;
cout << "Value of a after -= 3 : " << a << endl;
a *= 2;
cout << "Value of a after *= 2 : " << a << endl;
a /= 4;
cout << "Value of a after /= 4 : " << a << endl;
return 0;
}
Output
Value of a after += 5 : 15
Value of a after -= 3 : 12
Value of a after *= 2 : 24
Value of a after /= 4 : 6
Explanation
- a += 5 means a = a + 5
- a -= 3 means a = a - 3
- a *= 2 means a = a * 2
- a /= 4 means a = a / 4
Summary:
- Assignment Operators are used to assign values to variables.
- They help in writing short and clean code.
- C++ provides six main assignment operators.
- These operators are widely used in loops and calculations.