C language ------- the difference between i++ and ++i

The difference between i++ and ++i

i++Both and ++iare auto-increment operators in C language, their main difference lies in their execution order and return value.

i++It means to take the value of i first, and then add 1 to the value of i. That is to say, i++the value of is the original value of i, and i++after , the value of i will be increased by 1. For example:

int i = 5;
int a = i++; // a的值是5,i的值是6

++iIt means to add 1 to the value of i first, and then take the value of i. That is to say, ++ithe value of is the value after adding 1 to i, ++iand after , the value of i will also increase by 1. For example:

int i = 5;
int a = ++i; // a的值是6,i的值是6

Therefore, the difference between i++and ++iis their execution order and return value. If you simply want to increase i by 1, then both ways of writing are possible, but in some expressions, the i++return ++ivalue of sum may affect the result of the expression, and you need to choose which way to use according to the specific situation.

The underlying assembly difference

In most compilers, this is distinguished i++from the assembly code generated under the hood.++i

Taking x86 assembly language as an example, suppose there is a variable i with an initial value of 0, i++and ++ithe assembly code of sum is as follows:

; i++的汇编代码
mov eax, DWORD PTR [i]
add eax, 1
mov DWORD PTR [i], eax

; ++i的汇编代码
add DWORD PTR [i], 1
mov eax, DWORD PTR [i]

As can be seen from the above assembly code, i++the value of i will be loaded into the register first, then the value of i will be increased by 1 in the register, and finally the value after adding 1 will be written back to i; while it will be directly in ++ii Add 1 to the memory location, and then load the added value into the register.

So, from the point of view of the assembly code, i++one extra memory access needs to be made, ++iwhich does . This is one of the reasons why it is more efficient ++ithan . i++However, for modern optimizing compilers, they usually do various optimizations, so that the performance gap i++between and ++ibecomes very small.

Guess you like

Origin blog.csdn.net/qq_43577613/article/details/130450842