Table of Contents
Compound assignment operators combine an arithmetic operation with an assignment operation. They provide a shorter and more convenient way to update the value of a variable without writing the variable name twice.
Each compound assignment operator performs the specified operation using the current value of the variable and then stores the result back into the same variable.
Source Code #
#include <iostream>
int main()
{
int value = 20;
value += 5;
std::cout << "After += : " << value << '\n';
value -= 3;
std::cout << "After -= : " << value << '\n';
value *= 2;
std::cout << "After *= : " << value << '\n';
value /= 4;
std::cout << "After /= : " << value << '\n';
value %= 3;
std::cout << "After %= : " << value << '\n';
return 0;
}
Output #
After += : 25
After -= : 22
After *= : 44
After /= : 11
After %= : 2
Explanation #
- Compound assignment operators combine an arithmetic operation and an assignment into a single statement.
value += 5is equivalent tovalue = value + 5.value -= 3is equivalent tovalue = value - 3.value *= 2is equivalent tovalue = value * 2.value /= 4is equivalent tovalue = value / 4.value %= 3is equivalent tovalue = value % 3.- These operators make expressions shorter and improve code readability.
return 0;terminates the program successfully.