CKTIS / C++
Unary plus in `score =+ delta` versus binary addition
`score =+ delta` assigns the result of unary `+delta`. To add `delta` to the current value of `score` and store the result, use `score += delta`.
Version: ISO C++23; implementation support may vary
Syntax
score =+ delta; // parsed as: score = (+delta);
score += delta; // compound assignment: add and store
score = score + delta; // binary addition, then simple assignmentIn C++, =+ is not an operator: the compiler reads two tokens, = and +. So score =+ delta means score = (+delta). With int variables, it replaces score with delta instead of adding it. The code is valid, so a warning about the possible typo is not required.
Built-in unary + takes one operand and preserves its value without modifying it: +delta does not turn -3 into 3. It accepts arithmetic, unscoped enumeration, and pointer types. Integral promotion can change the result type, for example from bool to int.
In score + delta, built-in binary + with numeric operands computes a sum but does not store it. Built-in score += delta adds delta to the current value of score and stores the result. It works like score = score + delta except that the left operand is evaluated only once. For user-defined types, unary and binary operator+ are distinct overloads and need not behave like the built-in operators.
Examples
#include <iostream>
int main() {
int score = 10;
const int delta = -3;
score =+ delta;
std::cout << "=+ : " << score << '\n';
score = 10;
score += delta;
std::cout << "+= : " << score << '\n';
score = 10;
score = score + delta;
std::cout << "= +: " << score << '\n';
}
Result
=+ : -3 += : 7 = +: 7
Each case starts with `score == 10`, and `delta` is `-3`. The first statement overwrites the score with `-3`. The other two add `-3` to `10` and store `7`.
Related lessons
- C++ · Lesson 54 · Intermediate · Version: 2