Search code examples
operatorsconventions

Can "number += 1" be explained intuitively/mnemonically?


Previous research

In several languages (perl, python, php, etc.) there is the <value> += <increment> operator**, which increments a <value> by adding <increment> to it. This can be used in a for loop, which will cumulatively add <increment> to <value> with each iteration. This saves having to type more explicitly (verbosely): <value> = <value> + <increment>.

The trouble with this operator is that one often forgets whether it was += or =+. I often learn I have typed it the wrong way later, the hard way.

I thought I would finally learn the intuition in this PHP tutorial (01:35), but he fumbles it.

Question

  • Is there an intuitive "in plain english" way of explaining why it is += instead of =+ or was it some convention that was arbitrarily set once upon a time?

  • If "Yes" to the above, then what is this intuitive way of explaining why it is +=?

** Please let me know in comments what this operator is formally known as.


Solution

  • Putting the non-equals sign before the equals sign reduces perceived ambiguity: a-=b can only mean "Decrement a by b", but a=-b could also mean "Set a to the negated value of b".

    This wouldn't technically be ambiguous, since the C parsing rules are clear that token consumption is greedy (that is, if =- were an operator, the parser would always prefer to parse it as =- rather than = -), but clearly it would have been ambiguous from a readability standpoint.