C++ Assignment Operators

Assignment operators put a value into a variable. The basic one is the equals sign, but C++ also gives you shortcut operators that let you update a variable based on its current value in a single, tidy step.

The basic assignment operator

The equals sign = is the assignment operator. It takes the value on the right and stores it in the variable on the left. It does not mean 'equals' in the math sense, so read x = 5 as 'x becomes 5' rather than 'x is equal to 5'.

Storing and updating a value

#include <iostream>
using namespace std;

int main() {
  int score = 10;   // store 10 in score
  score = 25;       // replace it with 25

  cout << "Score: " << score << "\n";
  return 0;
}

Compound assignment shortcuts

Very often you want to change a variable based on its own value, such as adding to a total. Instead of writing total = total + 5, C++ lets you write the shorter total += 5. These combined operators are called compound assignment operators.

Common assignment operators

OperatorExampleSame as
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3

Compound assignment in a running total

#include <iostream>
using namespace std;

int main() {
  int total = 100;
  total += 50;   // total is now 150
  total -= 20;   // total is now 130
  total *= 2;    // total is now 260

  cout << "Total: " << total << "\n";
  return 0;
}
  • = assigns, it does not compare
  • Compound operators make code shorter and easier to read
  • The variable must already exist before you use += or its siblings
  • You can chain assignments, for example a = b = 0, which sets both to 0
Note: Compound assignment operators do exactly the same work as the long form, they are just a convenient shorthand. Pick whichever reads more clearly to you, but most C++ programmers prefer the short version.