The difference between i++ in C and java

Found through testing:

Run in Java language:

int i = 0;

i = i ++;

 The value of i is 0;

 

Run in C language:

int i = 0;

i = i ++;

The value of i is 1;

Isn't it weird?

 

The reason is simple: C and Java use different operating mechanisms for ++!

In the Java language:

Use intermediate variable mechanism:

For example:
i = i++;

Is equivalent to:

temp = i;
i = i + 1;
i = temp; 

Essence: In java, when performing an increment operation, a temporary variable is allocated,

++i: It will be assigned to temporary variables after adding 1;

i++: It will first assign a value to a temporary variable and then add 1";

The final use of the operation is not the variable itself, but the temporary variable that has been assigned a value.

 

In C language:

Self-increment mechanism:

int a = 0

int i = 0;

Figure out: a = i++ and i = i++; the results are different, why?

The i++ operation means to increment after returning the result.

The ++i operation means to increment before returning the result.

Then the result is obvious, a is 0, then why is i 1?

See the process: i = i++ => i = 0, i = i+1

i = 0 because the return value of i++ is 0, which is assigned

i = i+1 because i needs to increase!

Guess you like

Origin blog.csdn.net/qq_37061368/article/details/106683302