• Home
  • 3.7 Compound Assignment Operators

3.7 Compound Assignment Operators

View Categories

3.7 Compound Assignment Operators

< 1 min read

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 += 5 is equivalent to value = value + 5.
  • value -= 3 is equivalent to value = value - 3.
  • value *= 2 is equivalent to value = value * 2.
  • value /= 4 is equivalent to value = value / 4.
  • value %= 3 is equivalent to value = value % 3.
  • These operators make expressions shorter and improve code readability.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *