EMZETT.
Login

Assignment Operators

In short: Operators that assign a value to a variable — the simplest is =; combined variants like +=, -=, *= combine a calculation directly with the assignment.

In more detail: x += 5 is shorthand for x = x + 5 and saves typing as well as repeating the variable name. It’s important to distinguish this from the comparison operator == (see Comparison Operators) — confusing = and == in a condition is a classic, often hard-to-find mistake.

In Depth

The common compound assignment operators:

x += 5    equals    x = x + 5     (add and assign)
x -= 5    equals    x = x - 5     (subtract and assign)
x *= 5    equals    x = x * 5     (multiply and assign)
x /= 5    equals    x = x / 5     (divide and assign)
x %= 5    equals    x = x % 5     (modulo and assign)

Beyond pure brevity, compound assignment operators have a practical advantage: the variable name appears only ONCE, instead of twice like in the spelled-out variant — for long or complex variable names (e.g. user.cart.totalAmount += itemPrice instead of the spelled-out, twice-as-long variant), this reduces both typing effort and the chance of typos.

Confusing = (assignment) and == (comparison, see Comparison Operators) is one of the classic, persistent programming mistakes — in some languages (classically C), if (x = 5) is even syntactically valid and simply assigns x the value 5, instead of performing a comparison, with the expression then additionally counting as “true” (because 5 is not equal to 0) — the program appears to keep running normally, but behaves fundamentally wrong. Modern languages and linters now usually explicitly warn about an assignment within a condition, precisely because of this risk of confusion.

A special case is the increment/decrement shorthand (x++/x--), which shortens an assignment by exactly 1 even further — technically closely related to the compound assignment operators, but treated as its own operator pair in most languages, among other things because (depending on whether it’s before or after the variable) it can return the value BEFORE or AFTER the increment, which doesn’t occur with +=.

See also: Operators, Comparison Operators