Course Content
C++ Introduction
C++ Introduction
Compound Assignment Operator
A compound assignment operator is a combined operator that combines an assignment operator and an arithmetic (or a bitwise) operator.
The result of such an operation is assigned to the left operand (what is before the =
sign).
main
#include <iostream> int main() { int some_variable = 0; std::cout << "Old value of the variable: " << some_variable << std::endl; some_variable += 500; // using a compound assignment operator std::cout << "New value of the variable: " << some_variable << std::endl; }
Using another compound assignment operator:
main
#include <iostream> int main() { int value = 0; value += 20; // value = value + 20 std::cout << "value = 0 + 20 = " << value << std::endl; value -= 4; // value = value - 4 std::cout << "value = 20 - 4 = " << value << std::endl; value *= 4; // value = value * 4 std::cout << "value = 16 * 4 = " << value << std::endl; value /= 8; // value = value / 8 std::cout << "value = 64 / 8 = " << value << std::endl; value %= 5; // value = value % 5 std::cout << "value = 8 % 5 = " << value << std::endl; }
Thanks for your feedback!