Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Addition assignment operator (+=)

The += operator adds the right operand to the left operand's value and stores the result back. The built-in operator evaluates the left operand only once; it supports arithmetic and pointer movement.

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

Syntax

lhs += rhs

The built-in operator lhs += rhs combines addition and assignment: it behaves like lhs = lhs + rhs, but evaluates lhs only once. The left side must be a modifiable lvalue, such as a non-const variable. The expression produces an lvalue referring to that same object; the right operand is evaluated before the left operand.

For arithmetic operands, addition uses the usual arithmetic conversions, and the result is converted to the left side's type. Conversion can lose information; overflow during signed integer addition causes undefined behavior. For a pointer to a complete object type, the right operand must have integral or unscoped enumeration type: p += n moves by n elements, not bytes. If p is non-null, the result must remain within the same array or point one past its end. The pointer addition rule also requires the pointee type of p to be similar (in the C++ sense) to the array element type. If p is an unsigned int* pointing to an element of an int array, p += 1 has undefined behavior even if the next element is in bounds. If p is null and n is zero, the operation is well-defined and leaves p null.

In the example, values[index++] += 5 increments index only once and updates the first element. The expected output is 15 20 1. Do not mechanically rewrite this as an assignment that repeats index++.

Classes can overload operator+=; its behavior and return type then depend on the selected function, and equivalence to + and = is not guaranteed. This entry targets C++23; the cited site presents an evolving draft, not a frozen C++23 publication.

Examples

#include <iostream>

int main() {
    int values[] = {10, 20};
    int index = 0;
    values[index++] += 5;
    std::cout << values[0] << ' ' << values[1] << ' ' << index << '\n';
}

Result

15 20 1

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