Pre & post increment operator behavior in C, C++,

2019-01-01 07:16发布

DISCLAIMER: This is not a real-world example. It is just a theoretical question of how these languages work.

What exactly are the differences between C/C++, C#, and Java when it comes to post & pre increment operators?

This is what I get with VC++10, Java 1.6, and C# 4

int a = 2;
int b = a++ + a++;
int c = ++a + a++ + a++;

      +-----+------+------+----+
      |  C  | C++  | Java | C# |
+-----+-----+------+------+----+
| a   |  7  |  7   |   7  |  7 |
+-----+-----+------+------+----+
| b   |  4  |  4   |   5  | 5  |
+-----+-----+------+------+----+
| c   | 15  |  15  |  16  | 16 |
+-----+-----+------+------+----+

标签: c# java c++ c
24条回答
孤独寂梦人
2楼-- · 2019-01-01 07:21

The Java memory model ensures the order the loads and stores are done, so it should come out the same on any JVM (I believe).

It looks like C++ has the same order of operations, but once you use it twice on a line you start running into other stuff (Vlad is right there). If you try other C++ compilers, you may find they come up with different answers.

I'm sure C# has the same order of operations, but my guess is they have a memory model (like Java) that ensures consistency, but I don't have a lot of knowledge here.

查看更多
无色无味的生活
3楼-- · 2019-01-01 07:22
呛了眼睛熬了心
4楼-- · 2019-01-01 07:24
闭嘴吧你
5楼-- · 2019-01-01 07:26

Java and C# evaluate expressions from left to right, and the side-effects are visible immediately.

In C++, the order of evaluation of subexpressions is unspecified, and modifying the same object twice without an intervening sequence point is undefined behavior.

查看更多
梦醉为红颜
6楼-- · 2019-01-01 07:26
只若初见
7楼-- · 2019-01-01 07:26
登录 后发表回答