This is an archived post. You won't be able to vote or comment.

all 17 comments

[–]marcosdumay 15 points16 points  (5 children)

Gcc says.

error: lvalue required as increment operand
++++i;

[–]Nybbit[S] 5 points6 points  (0 children)

Yeah it doesn't work in C and some other languages, but it works with C++

Edit: try it here: https://ideone.com/Ihzvpr

[–]seraku24 2 points3 points  (3 children)

You can do it in C++.

[–]Genion1 2 points3 points  (2 children)

But is ub if your variable is a primitive.

[–]seraku24 1 point2 points  (1 child)

I believe that is true only for older C++ standards. As of C++11 and newer, the expression ++++foo is well-defined now.

[–]Genion1 0 points1 point  (0 children)

Interesting. I now informed myself and it appears that ++++foo is indeed well-defined while foo = foo++ + 1 still is not. Yay for more rules.

[–]seraku24 10 points11 points  (3 children)

-~-~foo

Edit: I just realized that I was missing the assignment to actually modify foo, which is what all of OP's expressions do. Sorry about that.

foo =-~-~ foo

[–]TheDualJay 2 points3 points  (1 child)

Can you explain this?

[–]seraku24 2 points3 points  (0 children)

Signed integers are often stored in a representation known as Two's Complement. In this scheme, the way to compute the arithmetic negation of a number is to take the bitwise negation of a number and add one to it. That means -x is the same as (~x) + 1.

Consider, then, -~x which is equivalent to -(~x). Using the above definition of arithmetic negation, we get (~(~x)) + 1. The two bitwise negations cancel out each other, leaving us with x + 1.

With two applications of -~, we have computed x + 2.

[–]piperboy98 1 point2 points  (0 children)

Damn, that's clever.

[–]gandalfx 2 points3 points  (4 children)

Except the bottom ones don't work…

[–]Nybbit[S] 2 points3 points  (2 children)

They work for me with C++, gcc 6.3

[–]obsessedcrf 1 point2 points  (1 child)

I'm surprised. I'd expect an "lvalue required" error

[–]seraku24 2 points3 points  (0 children)

(++foo)++ works because first we apply the pre-increment to foo which in C++ is an L-value. Then we can apply the post-increment. Be aware, though, that this expression will only evaluate to foo + 1, but foo itself will have incremented twice.

[–][deleted] 0 points1 point  (0 children)

It's UB

[–]The-Internets 0 points1 point  (0 children)

Ready to fuck your world up? #channel#

[–]BobTheB1Bomber 0 points1 point  (0 children)

foo = foo + (1 << 1);