The underlying principle of i++ and ++i in C#

I. Introduction

We all know that i++ is to take the value first and then calculate it. ++i is to calculate first, then take the value. Let's talk about its underlying principle

Operator priority and operation order:
The operator priority only affects the combination order in the expression, and does not affect the operation order. The operation order is always calculated from left to right.
For example, the following code:
int x = 3;
int y = 1 || (x = 1) && (x += 1);
run Then x=3, y=1. Because although && has a higher priority than ||, it is still calculated from left to right during operation, and the short-circuit effect of || causes no need to calculate after ||


Two: principle

int i = 0;
i++;
Console.WriteLine(i);

The result is 1.
The execution steps are:
1. Push the constant 0 into the operand stack
2. Take out the element 0 from the stack, and then push the local variable + 1 into the stack
3. When outputting, take the top element 1 of the stack 
whether it is i++ or + +i, the underlying execution is the same, because ++ is not used as an assignment expression symbol here, and the underlying layer is regarded as just the operation of +1 to the variable, so there is no difference


 

int i = 0;
i = i++;
Console.WriteLine(i);

The result is 0.
The execution steps are:
1. Push the constant 0 into the operand stack
2. Take out element 0 from the stack, put 0 into the stack, and then add 1 to the value of the local variable i, at this time i=1, then When assigning a value, assign the element in the stack to i, and i is assigned a value of 0, and then put it on the stack.
3. When outputting, take the top element 0 of the stack
because i++ will create a temporary variable, so using ++i will reduce the creation of a variable, but This performance optimization is negligible for a value type variable


 

int i = 0;
i = ++i;
Console.WriteLine(i);

The result is 1.
The execution steps are:
1. Push the constant 0 into the operand stack
2. Take out element 0 from the stack, add 1 to the value of the local variable i, at this time i=1, and then push it into the stack 3. Fetch
when outputting top element 1


 

int i = 1;
i = ++i + i++;
Console.WriteLine(i);

The result is 4.
The execution steps are:
1. Push the constant 1 into the operand stack
2. Take the element 1 from the stack and assign it to i, add the value of i + 1 to equal 2 and then push it into the stack. At this time, i=2.2 Push it into the stack again, and then add 1 to the value of i. At this time, i=3. When calculating, use 2 and 2 in the operand stack to add the result to 4, then assign it to i, and then push i into the stack. 3. When
outputting Take the top element of the stack 4


Three: Summary

i++ is pushed into the stack first and then +1, ++i is +1 first and then pushed into the stack

Guess you like

Origin blog.csdn.net/LLLLL__/article/details/132018966