Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

i += ++i;

what should be the result ? what is the result in C++ ? (undefined)



If you're making a new language, that example could go a couple of ways:

1. It could be a compiler error. The existence of certain operators doesn't mean they can be combined arbitrarily.

2. Sequence points could be defined differently, allowing for such a convoluted line. This would likely hurt performance, as the compiler would have fewer operations to reorder in each sequence point.

Typically, increment and decrement are just syntactic sugar. I don't mind if a language lacks them, but I can see why people like them. A convoluted example of UB in C++ is not a good argument against having them.

Also: In C++, overloaded operators are function calls, and function calls are sequence points. So if i is an object, the behavior is defined. That said, it would still be bad code. :)


I am not sure about if 2 actually would hurt performance in the real world. Remember the whole "must appear to be in order" thing. If the compiler knows that it doesn't change things if they are out of order, it's free to rearrange them.

Note: things like this are part of the potential advantages of static linking.


This could actually work fine in Rust, because it has deterministic evaluation ordering for everything (or almost everything, though I can't think of anything that isn't deterministic).

Knowing that `++i` is `{ i += 1; i }`, we have `i += { i += 1; i };` (which should compile already).

The nested assignment can be hoisted to obtain `i += 1; i += i;`.

That means Rust would compile `i += ++i;` as `i = (i + 1) * 2;`.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: