Transferred from: Chinese version of "C and pointer", p396
Now we can infer why the parameters are pushed to the stack in reverse order of the list. The called function adds an offset to the frame pointer to access the parameter. When the parameters are pushed to the stack in reverse orderFirst ParameterIt is located at the top of the heap parameter in the stack, and its offset from the frame pointer is a constant. In fact,AnyThe offset of a parameter from the frame pointer is a constant, which is irrelevant to the number of parameters in the stack.
What if the parameters are pushed to the stack in reverse order (that is, in the parameter list order )? In this way, the offset of the first parameter from the frame pointer is related to the number of parameters pushed into the stack. The compiler can calculate this value, but there is still a problem-the number of actually passed parameters may not be the same as the number of parameters the function expects to accept. In this case, the offset is incorrect.
In the reverse-Order Scheme, how does one deal with additional parameters? The stack frame graph shows any additional parameters. When the parameters are in the first few parameters,First ParameterThe distance from the frame pointer remains unchanged. Therefore, the function can correctly access the first three parameters and ignore the additional parameters.
Appendix:
Why can the number of actually passed parameters in C be different from the number of parameters expected to be accepted by the function:
Because the method signature of C does not contain parameters, that is, int Foo (int A) and INT Foo (int A, int B) cannot appear at the same time, which is different from C ++.