Plus-Minus Operator in C
how the increment operators are fully orthogonal
2020-10-01
The C language has some features that try to achieve orthogonality. For instance, there's both an increment operator ++
and decrement operator --
.
I don't think many C programers realize that this is fully orthogonal, with the plus-minus operator +-
and minus-plus operator -+
, which are combinations of the increment and decrement operators, and result in an unchanged value.
#include <stdio.h> int main() { int i = 3; printf("i: %d\n", i); // 3 ++i; printf("++i: %d\n", i);// 4 --i; printf("--i: %d\n", i);// 3 +-i; printf("+-i: %d\n", i);// 3 -+i; printf("-+i: %d\n", i);// 3 }
Of course I'm kidding, but not exactly how you might think.
I'm not kidding about this code working as I claim, it does compile and +-
and -+
really do leave i
unchanged.
I'm kidding about +-
and -+
being whole operators on their own. This is similar to the "goes to" operator -->
. They're not operators on their own, but a combination of multiple operators, in this case the negation operator -
and the unary plus operator +
.
The unary plus operator may be the part that makes this trick work because I don't think it's that well known. How it works, the negation and unary plus operator don't change the value of their operand, so in the above code the operator is applied then we just drop the value. You'll see an unused value warning if you turned them on.
If you thought the reason I'm kidding is because they wouldn't have added operators that do nothing just for the sake of symmetry, well that's where you're wrong. Because the unary plus operator is just that. It's like negation, but not negating, so it gives you the same value. (Ok, it doesn't do "nothing", but really it is just the same value.)
And it really was added just so we have something matching the negation operator. From K&R second edition:
The unary + is new with the ANSI standard. It was added for symmetry with the unary -.