Operator transposition

submited by
Style Pass
2024-11-30 04:30:06

Did you know that you can mistype a += b as a =+ b and it’ll still compile/run, so long as the language you’re programming in has a unary plus operator, and the return type of +b is assignable to a?

Did you know that it’s even easier to make the same mistake with a -= b as a =- b because unary minus seems to be more commonly available?

Did you know that you can also do this with if (a != b) as if (a =! b) in cases where the result of an assignment expression can be interpreted as a bool, a is mutable, and the unary not operator is also a thing that exists?

Did you know that these mistakes might be slightly easier to spot if you use a code formatter that rearranges the whitespace to a = +b etc,[3] but even that still depends on the reader noticing the discrepancy between the intended behavior and the code as written, and in the case of a = -b it might even be harder to spot that something’s wrong?

Did you know that in JavaScript you can typo if (a >= b) as if (a => b) and neither immutability nor the formatter will save you?[4]

Leave a Comment