Assignment Operators

Assignment Operators in C++

Learn about C++ assignment operators: the = operator, compound forms like += and -=, chaining, and common mistakes, with short code examples.

On this page
  1. What the assignment operator does
  2. Compound assignment operators
  3. Chaining assignments
  4. The left side must be assignable
  5. Assignment converts the value
  6. Assignment is not comparison
  7. Copy assignment for classes
  8. Summary

What the assignment operator does

The assignment operator, =, stores a value in a variable. In total = price * 2;, the right side is computed first, and the result is stored in total. The left side has to be something that can hold a value, which is usually a variable.

Here is a short program that assigns a few values:

#include <iostream>

int main() {
    int count = 0;      // initialization: count starts at 0
    count = 5;          // assignment: count now holds 5
    count = count + 2;  // assignment: count now holds 7

    std::cout << count << '\n';  // prints 7
    return 0;
}

The first = is part of the declaration, so it sets the starting value. The later ones assign a new value to a variable that already exists. All three use the same symbol.

Compound assignment operators

C++ also has assignment operators that combine another operation with assignment. x += 3; means the same as x = x + 3;, and the other forms follow the same pattern:

  • +=, -=, *=, /=, and %= for addition, subtraction, multiplication, division, and remainder
  • &=, |=, and ^= for bitwise AND, OR, and XOR
  • <<= and >>= are the compound forms of the shift operator in C

The left side is evaluated only once, which matters when it has side effects. In values[i++] += 2;, the index i goes up by one, and the element at the old index is changed.

The += operator also works on std::string, where it appends text:

#include <iostream>
#include <string>

int main() {
    int total = 10;
    total += 5;  // total is now 15
    total *= 2;  // total is now 30

    std::string greeting = "Hello";
    greeting += ", world";  // greeting is now "Hello, world"

    std::cout << total << '\n' << greeting << '\n';
    return 0;
}

The program prints 30 on one line and Hello, world on the next. For more ways to join text, see how to concatenate strings in C.

Chaining assignments

Assignment works from right to left and produces the value it stored, so several assignments can be chained in one statement:

int a, b, c;
a = b = c = 0;  // c is set first, then b, then a

Chaining is legal, but it can be hard to read. Many programmers keep one assignment per line.

The left side must be assignable

The left operand has to be an lvalue, which means something with a memory location that can be changed. A variable qualifies. A literal such as 5 does not, and neither does a calculation such as a + b. Both of these lines fail to compile:

5 = x;      // error: a literal cannot be assigned to
a + b = c;  // error: the result of a + b is not a variable

A variable declared const cannot be assigned after it is set either:

const int limit = 10;
limit = 20;  // error: limit is const

Compilers word these errors differently, but the idea is the same: the left side must be something you can assign to.

Assignment converts the value

The value on the right is converted to the type of the variable on the left. This can drop information:

int n = 3.9;  // n holds 3; the fraction is dropped
int m{3.9};   // error: narrowing conversion in brace initialization

Integer division can also surprise people, because the division happens before the assignment:

int total = 7;
double average = total / 2;  // total / 2 is 3, so average holds 3.0, not 3.5

Assignment is not comparison

= assigns a value, and == compares two values. Mixing them up is a common bug:

int count = 0;
if (count = 5) {  // assigns 5 to count; 5 is not zero, so the body runs
    // ...
}

Many compilers warn about this when warnings are turned on. To check whether two values are equal, use ==.

Copy assignment for classes

When both sides are objects of a class, = calls an assignment operator for that class. If the class does not define one, C++ usually generates one that copies each member. Writing your own is one use of operator overloading in C.

Here is a small example:

#include <iostream>

struct Point {
    int x;
    int y;
};

int main() {
    Point a{1, 2};
    Point b{0, 0};
    b = a;  // copy assignment: b's x and y are overwritten with a's values

    std::cout << b.x << ' ' << b.y << '\n';  // prints 1 2
    return 0;
}

The line Point c = a; looks similar, but it creates a new object. That is initialization, not assignment, because the = in a declaration sets the starting value of a new object.

Summary

  • = stores the value on its right in the variable on its left.
  • Compound forms such as += and <<= combine an operation with assignment.
  • The left side must be a variable that can be changed, not a literal, a calculation, or a const variable.
  • The value is converted to the variable’s type, which can drop a fraction.
  • = assigns, and == compares.

Keep exploring

Guides from other topics

All topics →