Hacker News new | ask | show | jobs
by kreco 814 days ago
> Because ++ and -- always have in-place update semantics, we never need to remember "use prefix ++/-- unless you need a copy of the old value." If you do need a copy of the old value, just take the copy before calling ++/--

I actually wish ++ and -- operators were removed. This would simplify everything, nothing to remember whether it's prefix or postfix operator, whether it copies something or not, you would just do "value += 1" and be done with it.

- Less mental overhead.

- Remove an extra way of doing the same thing.

3 comments

Unfortunately, C++ uses ++ and -- for iterators, many of which cannot reasonably implement += or -=. This distinction is baked into the type system to tell whether or not an iterator supports efficient "multiple advance" (e.g. a linked list iterator doesn't have += but a pointer into a contiguous vector does).

There's no way to fix this in a reverse-compatible way for existing code (which is one of the constraints of cpp2- it must work with all existing C++ so that it is possible for existing projects to migrate regardless of size).

Making ++ or -- a statement that increment the target without returning a value should probably be enough for forward iterators.
A noncopying ++ could be spelled `+= 1` though. So some iterators would support `+= 1`, but not `+= 2`. This would be vaguely similar to how the null pointer constant was defined as an integer constant expression that evaluates to zero: Define `+= <integer constant expression that evaluates to one>` as the increment operator.
Rust and Go made the same choice. In Go, I think i++ is valid - but only as a statement, not an expression.

https://go.dev/doc/faq#inc_dec

But you would break the name! C++ would be a syntax error!

I mean, there are people that already think that...

We could allow overloading operator++ while not defining it on anything built-in....
But it’s C++2, and that would become valid! (C + +2)