views:

37

answers:

1

I recently read: "The expressions (++i) and (i++) have values and side effects. The side effect is that the value in i is increased by 1. The value of (i++) is the value before the increment and the value of (++i) is the value after the increment, but whether the increment or the evaluation takes place first, is not part of C."

I know the evaluative step takes place first in Java... is it the same for all other languages?

+2  A: 

At least in C++, operators can be overloaded, so the semantics of ++i and i++ are not guaranteed - they can in fact be overloaded to do very different things, and can even be made to do something that has nothing to do with increment. So the answer to your question is that no - in at least one language, the postfix and prefix ++ operator for classes can do whatever the programmer wishes.

But just because someone can do that, it doesn't mean they should. Since the pre- and post-increment operators have very well known semantics, (decent) C++ programmers try to not violate that, lest the code that uses them will be most surprised.

A good example of operator overloading in C++ is the STL iterators. Iterators to containers like linked lists define a class that overloads the preincrement and postincrement operators in such a way that it mimics a pointer (iterators in C++ are in fact a generalization of pointers).

In silico
Cool. Thank you for the thoughtful reply! Aside from overloading I was wondering if there are (computationally) different implementations.
sova
@sova: Probably not. The `++` operator is made "famous" by C-like languages like C, C++, Java, C#, etc. to mean "increment this variable," with well-known side effects.
In silico