Assignment Operators

What Does Assignment Operator Mean?

The assignment operator is the equals sign, =. It stores the value on its right in the variable on its left, as this short example clearly shows.

On this page
  1. The short answer
  2. How it reads in a program
  3. Assignment is not comparison
  4. Assignment and initialization
  5. Compound forms

The short answer

The assignment operator is the single equals sign, =. It takes the value on its right and stores it in the variable on its left. In age = 31;, the number 31 goes into age, replacing the value age held before.

How it reads in a program

Here is a short program that uses it:

#include <iostream>

int main() {
    int age = 30;              // the variable age starts out holding 30
    age = 31;                  // the assignment stores 31 in age
    std::cout << age << '\n';  // prints 31
    return 0;
}

The right side can be any expression. In total = price * 2;, the multiplication runs first, and its result is stored in total.

Assignment is not comparison

It is easy to confuse = with ==. A single = changes a variable. A double == checks whether two values are equal and gives a true or false result. Writing if (age = 30) assigns 30 to age instead of checking it, and because 30 is not zero, the body of the if runs.

Assignment and initialization

In int age = 30;, the equals sign sets a starting value when the variable is declared. This is called initialization. Later lines such as age = 31; assign a new value to a variable that already exists. Both use the same symbol, so it helps to notice whether a variable is being declared or changed.

Compound forms

C++ also has compound forms such as +=, which combine a calculation with assignment. age += 1; adds 1 to age, just like age = age + 1; does.

The complete guide to assignment operators

Assignment Operators in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Heap vs Stack Memory in C++

Learn how heap and stack memory differ in C++: how each is allocated, how long data lives, the speed and size trade-offs, and common mistakes, with examples.

Heap vs Stack 5 min read

Is C++ Better Than C?

C++ grew out of C and adds classes, templates, and a large standard library. Neither is better in every case. See how they differ and which suits your goals.

C++ vs C 4 min read