Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is putting an arbitrary number of pre-increment/decrement operators together possible in C++?

Today, I noticed that it is possible to do something like this (C++):

int x = 3;
++++x; // Correct!
----x; // Correct, too!
++++++x; // x is now 6

That means we can put as many as pre-increments and pre-decrements together. Am I right? I know it will not be a good practice, however, should we use it or for example, does ++++x perform better than x += 2?

By the way, it is impossible to use post-increments and post-decrements in that way:

int x = 3;
x++++; // Error
x----; // Error

Why?

And my last question is, why it doesn't work in C#, Java, JavaScript, PHP or even C? (Note: I don't say Python and Ruby because they have none of postfix/prefix increment/decrement operators)

Thanks in advance!

like image 746
MAChitgarha Avatar asked Jan 25 '26 10:01

MAChitgarha


1 Answers

Both prefix and postfix increment need a reference to the value to be incremented.

++x returns an lvalue to the incremented x, which can be incremented again. That's why prefix increment can be chained.

Postfix x++ however, increments x and returns a temporary copy of the previous value, so the second postfix increment would apply to this temporary.

Performance is not relevant here. ++++x and x+=2 are equivalent - some compiler might generate better code for one or the other, but that's not expected, and even then the difference will be usually negligible on most execution platforms.

While ++++x is legal, it will usually be considered bad style.


As for why other languages don't do that: I am not aware of an rationale, though "don't help programmers write weird code" might be plausible. It might also simply be a side effect of other rules. Be aware that in other languages the expression evaluation rules are notably different. E.g., x = x++ + 1; ~~is~~ was undefined behavior in C and C++, but not in C#.

like image 192
peterchen Avatar answered Jan 27 '26 00:01

peterchen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!