Hi Everybody,
I attended a technical interview a few days ago, and I was asked How does the C compiler implments function with Variable number of arguments? How does it pass the on the stack?
Does anyone know or can explian that?
Thanks, Dan
Hi Everybody,
I attended a technical interview a few days ago, and I was asked How does the C compiler implments function with Variable number of arguments? How does it pass the on the stack?
Does anyone know or can explian that?
Thanks, Dan
As far as I know, with C...
the caller function pushes arguments onto the stack in right-to-left order.
the caller is responsible for removing the arguments from the stack after the called function has executed. This is probably precisely because the caller is guaranteed to know how many arguments it put on the stack, while the called function might get it wrong.
P.S.: Calling conventions are usually implementation-specific. What I just described is known as the "cdecl" calling convention. Contrast this to a calling convention generally known as "stdcall", where the called function is responsible for removing its arguments from the stack. Because of that, it does not support variable-length argument lists.
P.P.S.: As user nategoose commented, I didn't mention how variable argument lists are actually used. See e.g. the POSIX documentation for the <stdarg.h>
header for more information.
It implements them using the va_ macros - for example va_start. Exactly what these macros do is implementation defined - in other words it will vary from CPU architecture to architecture, and from compiler to compiler. But they must play tricks with the C call stack. Typically, this will involve taking the address of the last named parameter as a base, and then accessing the variadic parameters by performing pointer arithmetic on this base.
Look into va_start, va_arg, and va_end. Here is a ton of info on this.
As far, as you sad that you got this question on tech interview, I'll assume that correct answer would be:
Caller will push explicit parameters to stack, count of variable parameters and variable parameters itself. Then target function code will be responsible for pop-ing all parameters out based on passed count and it's stack address.
And add a some ideas, why placing this parameters in separate array is not convenient.