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:33
情到深处是孤独
3楼-- · 2019-01-01 07:34
| Trace

int a= 2;                     a=2
int b= a++ + a++;             a=2, a=3

here value of a=4

int c = ++a + a++ + a++;      a=5, a=5, a=6

here value of a=7

In C/C++

Statement Trace

int a= 2;                     a=2
int b= a++ + a++;             a=2, a=2

here value of a=4

int c = ++a + a++ + a++;      a=5, a=5, a=5

here value of a=7

In short in java expression goes left to right so at the 2nd "a" it will fetch new value and in c/c++ it will first evaluate whole expression and then increment all operands of statement.

查看更多
伤终究还是伤i
4楼-- · 2019-01-01 07:36

I like this question and found very good explanations but I just want to explain this question by it's value how it is evaluated:

I will only talk about java and c/C++ as I have no knoledge about C#

Statements are evaluated in following ways

In java

Statement

查看更多
明月照影归
5楼-- · 2019-01-01 07:36
旧时光的记忆
6楼-- · 2019-01-01 07:38
春风洒进眼中
7楼-- · 2019-01-01 07:40
登录 后发表回答