开发者

Does implementation of ++i vs. i++ vary from language to language?

I recently read: "The e开发者_开发百科xpressions (++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?


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜