JRBros
JRBros

Reputation: 43

Is increment stackable? I.e x++++; or (x++)++;

When me and my friend were preparing for exam, my friend said that x+++; is the same as x+=3;

It is not true but is x++++; same as x+=1; or is (x++)++;? Could I generalize it? I.e. x++++++++++++++; or ((((((x++)++)++)++)++)++)++; is equivalent to x+=7;

Maybe it's completely wrong and it is true for ++++++x; or ++(++(++x)); equivalent to x+=3;

Also it should generalize to --x; and x--;

Upvotes: 1

Views: 596

Answers (1)

Alan
Alan

Reputation: 1

The behavior of your program can be understood using the following rules from the standard.

From lex.pptoken#3.3:

Otherwise, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token, even if that would cause further lexical analysis to fail, except that a header-name is only formed within a #include directive.

And from lex.pptoken#5:

[ Example: The program fragment x+++++y is parsed as x ++ ++ + y, which, if x and y have integral types, violates a constraint on increment operators, even though the parse x ++ + ++ y might yield a correct expression.  — end example ]


is x++++; same as x+=1;

Using the statement quoted above, x++++ will be parsed as x++ ++.

But note that from increment/decrement operator's documentation:

The operand expr of a built-in postfix increment or decrement operator must be a modifiable (non-const) lvalue of non-boolean (since C++17) arithmetic type or pointer to completely-defined object type. The result is prvalue copy of the original value of the operand.

That means the result of x++ will a prvalue. Thus the next postfix increment ++ cannot be applied on that prvalue since it requires an lvalue. Hence, x++++ will not compile.

Similarly, you can use the above quoted statements to understand the behavior of other examples in your snippet.

Upvotes: 2

Related Questions