CKTIS / C++
Subtraction assignment operator (-=)
The -= operator subtracts the right operand from the left operand's value and stores the result in the left object. For the built-in operator, the left operand is evaluated only once; type conversions and pointer arithmetic restrictions still apply.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
lhs -= rhsBuilt-in lhs -= rhs 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; assignment operators group right-to-left.
For numbers, subtraction uses the usual arithmetic conversions, and the result is then converted to the left object's type. Thus, int count = 10; count -= 2.5; stores 7: conversion discards the fractional part. Signed integer arithmetic overflow is undefined behavior; arithmetic in an unsigned type operates modulo 2^N. Account for promotions and conversions rather than assuming the calculation occurs in the left side's type.
A pointer to a complete object type can use -= with an integer. The offset counts elements, not bytes. For a non-null pointer, the result must remain within the same array or one past its end. In C++23, if p is a null pointer, p -= 0 is well-defined and leaves p null. Subtracting two pointers with - does not mean pointer -= other_pointer is allowed.
In the example, values[i++] -= 3 increments i only once. Class types can overload operator-=; its behavior and result type depend on its declaration, and equivalence to lhs = lhs - rhs is not guaranteed.
Examples
#include <iostream>
int main() {
int values[] = {10, 20};
int i = 0;
values[i++] -= 3;
int count = 10;
count -= 2.5;
std::cout << values[0] << ' ' << values[1] << ' ' << i << '\n';
std::cout << count << '\n';
}
Result
7 20 1 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.