C++ Assignment Operators

Assignment operators in C++ are used to assign values to variables. They combine arithmetic operations with assignment to simplify code.

List of Assignment Operators

OperatorDescriptionExample
=Assigns a value to a variableint x = 5;
+=Adds right operand to the left operand and assigns the result to leftx += 3; // x = x + 3
-=Subtracts right operand from the left operand and assigns the result to leftx -= 2; // x = x – 2
*=Multiplies left operand by right operand and assigns the result to leftx *= 4; // x = x * 4
/=Divides left operand by right operand and assigns the result to leftx /= 5; // x = x / 5
%=Calculates modulus of left operand by right operand and assigns result to leftx %= 3; // x = x % 3

Example Program

#include <iostream>
using namespace std;

int main() {

    int x = 10;
    int y = 5;

    x += y;  // x = 10 + 5 = 15
    cout << "x after += y: " << x << endl;

    x -= 3;  // x = 15 - 3 = 12
    cout << "x after -= 3: " << x << endl;

    x *= 2;  // x = 12 * 2 = 24
    cout << "x after *= 2: " << x << endl;

    x /= 4;  // x = 24 / 4 = 6
    cout << "x after /= 4: " << x << endl;

    x %= 5;  // x = 6 % 5 = 1
    cout << "x after %= 5: " << x << endl;

    return 0;
}

Output

x after += y: 15
x after -= 3: 12
x after *= 2: 24
x after /= 4: 6
x after %= 5: 1

Next Topic

Next, learn about C++ Comparison Operators.