Details and examples of the push order of function parameters in C language

  • 2020-05-12 02:56:24
  • OfStack

Details and examples of the push order of function parameters in C

People who are dedicated to technology, such as me, tend to be "aware" of some problems and want to "know why" as well as "know why". C language is extensive and profound, even though I have many years of development experience, there are still many problems I do not know why. Someone, somewhere, asked me the other day, what is the order in which function arguments are pushed in C? From right to left, I answered casually. Why from right to left? I didn't give a reasonable explanation after all. So, had to do a homework, so had this small blog.


#include

void foo(int x, int y, int z)
{
    printf("x = %d at [%X]n", x, &x);
    printf("y = %d at [%X]n", y, &y);
    printf("z = %d at [%X]n", z, &z);
}

int main(int argc, char *argv[])
{
    foo(100, 200, 300);
    return 0;
}

Operation results:


x = 100 at [BFE28760]
y = 200 at [BFE28764]
z = 300 at [BFE28768]

The C program stack has a high address at the bottom and a low address at the top, so the above example shows that function arguments are indeed pushed from right to left. But why? A review of the literature shows that the parameter push order is related to the specific compiler implementation. For example, parameters in Pascal are pushed from left to right, and you can specify them with modifiers in some languages, such as VisualC++. Why should C choose to go from right to left when it can go either way?

A step further shows that the Pascal language does not support variable length arguments, a feature that the C language does, which is why C function arguments are pushed from right to left. The reason for this is that the C push order (from right to left) has the advantage of dynamically changing the number of parameters. According to the stack heap analysis, the first parameter is pushed at the bottom of the stack when the stack is pushed from left to right. Unless you know the number of parameters, you can't get the leftmost parameter from the relative displacement of the stack pointer. So you have an indeterminate number of parameters on the left, which is the opposite of the number of dynamic parameters.

Therefore, C language function parameters are pushed from right to left, mainly to support the variable length parameter form. In other words, if this feature is not supported, the C language is completely like Pascal1, with the parameter pushing from left to right

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: