and a ++ ++ a, C ++ parameter passing in turn

Look at the piece of code:

#include<iostream>
using namespace std;

void func(int a, int b)
{
    cout << a << " " << b << endl;
}

int main()
{
    int a = 0;
    func(a++, ++a);
    return 0;
}

Because C ++ is from right to left on the stack (call the relevant agreement with the compiler, not the provisions of the C ++ standard), so just see the code, I think that the result will be "11" (++ a first stack and then a ++ stack), but the fact is: . This is on top of VS running on g ++ is the same result. Fortunately, VS can also view assembly code.


Since there is very convenient disassembly tool in VS, so the next thing to say is based on VS2019 comes disassembled.
Set breakpoints and debug, you can open the disassembly window:



the following piece of assembly code that is invoked when the function func:

mov         eax,dword ptr [a]
add         eax,1  
mov         dword ptr [a],eax  //这三行指令将a+1
mov         ecx,dword ptr [a]  
mov         dword ptr [ebp-0D0h],ecx  //这两行指令将a的值存储到一个临时地址(寄存器间接寻址)中
mov         edx,dword ptr [a]  
add         edx,1  
mov         dword ptr [a],edx  /这三行指令又将a+1
mov         eax,dword ptr [a]  
push        eax   //这两行指令将a压入栈
mov         ecx,dword ptr [ebp-0D0h]  
push        ecx  //这两行指令将刚刚存储的临时地址的值压入栈

call        func (0A312E9h)  //调用func函数
add         esp,8  //esp为栈指针寄存器  

If the code is changed

func(++a, ++a);

What would result? the answer is

mov         eax,dword ptr [a]  
add         eax,1  
mov         dword ptr [a],eax  //这三行指令将a+1
mov         ecx,dword ptr [a]  
add         ecx,1  
mov         dword ptr [a],ecx  //这三行指令将a+1
mov         edx,dword ptr [a]  
push        edx   //这两行指令将a压入栈
mov         eax,dword ptr [a]  
push        eax   //这两行指令将a压入栈

call        func (09912E9h)  
add         esp,8 

Can be seen, the change after a ++ a ++, command less the value of a step to save up , and since it is not when reading the parameters onto the stack, but only after all the parameters of executing the expression press-fitting, the final parameters of the stack are pressed into the final variable a.
Then the combined assembly code to understand why the beginning of the article is "12" is not difficult, is such a fundamental difference (Note: When reading the parameters and performance parameters of expression is from right to left) :

when calling the function, to avoid the use of parameter increment and decrement, to avoid confusion.


Write articles for local authors read in conjunction with the individual, there may be mistakes, if wrong, please correct me.

Guess you like

Origin www.cnblogs.com/fancyxie/p/11618369.html