Domanda

When a function call is made in C, the arguments are passed in the reverse order. This is important so that we have access to the first argument. And this some how supports varargs. I don't understand that even if you have access to the first argument, you would still need to know how many arguments the function has, otherwise you might easily slip past the last argument and start considering invalid values as arguments.

And if the argument count is required, then there is no point in passing arguments in the reverse order because you can access the first argument with (sp - 2 * number_of_arguments, sp = stack pointer.

Passing arguments in the reverse order is also supposed to help recursive calls, I don't understand how.

Thank you in advance.

È stato utile?

Soluzione

C does not define the order in which arguments are passed. In fact, some very common calling conventions (like the x86-64 SYSV ABI) pass the first several arguments in registers, with no order at all.

However, it is true that it is very common for variable-argument-list functions to have their argument pushed onto the stack from last to first. This is because the code emitted for the called function has to work with any number of additional arguments passed. You are right that the calling convention could include passing the number of additional arguments - but passing the arguments in reverse order means that this is not required, so it is a simpler option. You are correct that it is easy under this scheme to start examining values beyond the last argument passed - this is what tends to happen for example if you pass insufficient arguments to printf() for a given format string.

Functions with a fixed number of arguments can be passed in either order, and in fact left-to-right calling conventions do exist (the 16-bit Windows API used such a calling convention).

Altri suggerimenti

In theory there is no preference to how a compiler generates code to store parameters on a stack or in registers. It really depends on the architecture of the target machine.

Having said that, where did you get the idea that they had to be in reverse order. A citation would be nice to evaluate your question.

So, the real answer, is it depends on what the compiler writer wishes to do.

finally, note this is analogous to Reverse Polish Notation: AB+ means A+B or Prefix Notation where +AB means A+B. Thus, so long as the compiler is consistent then ordering is immaterial.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top