Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

Addition assignment operator (+=)

The += operator adds the right operand to the left and stores the result on the left, evaluating the destination only once.

Version: C23; repository compiler flag, production runtime not attested

Syntax

lhs += rhs

lhs += rhs works like lhs = lhs + (rhs), but evaluates lhs only once. The left operand must be a modifiable lvalue.

Operands may be arithmetic; addition rules and conversion back to the destination type apply. Signed addition overflow is undefined behavior. An integer can be added to a pointer to a complete object type. The offset is measured in elements, and the result must point to an element of the same array or one past its last element. For pointer arithmetic, an object that is not an array element is treated as the sole element of a one-element array. Thus, adding 1 with += to a pointer to such an object validly produces a pointer one past that object.

Single evaluation does not order the operands. For atomic lhs, this is an atomic read-modify-write operation with memory_order_seq_cst ordering.

In the example, values[i++] += 5 increments i only once.

Examples

#include <stdio.h>

int main(void)
{
    int values[] = {10, 20};
    int i = 0;
    values[i++] += 5;
    printf("%d %d %d\n", values[0], values[1], i);
    return 0;
}

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