Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Assignment operator (=)

The = operator assigns a value to an existing object. Learn the left-operand requirements, value conversion, chained assignment, and the distinction between assignment, initialization, and comparison with ==.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

lhs = rhs

The built-in = operator replaces the value of an existing object. Its left operand must be a modifiable lvalue, such as a non-const variable of type int. The right-hand expression is implicitly converted to the left operand's type without top-level qualifiers. Conversion can lose information; int n{0}; n = 3.9; stores 3.

Assignment groups right-to-left: a = b = 7 means a = (b = 7). The result of built-in assignment is an lvalue referring to the left operand. The right operand is evaluated before the left operand. In the example, both objects receive 7, and the later a = 3 changes only a.

Do not confuse assignment with initialization or comparison. In the declaration int a = 0;, the = token belongs to initialization syntax; it does not invoke the assignment operator. The expression a == 3 tests equality, whereas a = 3 changes a. Accidental assignment in a condition can therefore change data instead of comparing it.

For class objects, operator= is a non-static member function; it can perform copy assignment, move assignment, or other defined behavior. The requirements and result of the built-in operator do not describe every overload. This entry targets C++23; the supplied site publishes an evolving working draft, not a frozen C++23 publication.

Examples

#include <iostream>

int main() {
    int a = 0;
    int b = 0;
    a = b = 7;
    a = 3;
    std::cout << a << ' ' << b << '\n';
}

Result

3 7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources