Why use this?

Why use va_start, va_arg, and va_end in order to make a function accept a variable number of arguments?

Cant it be done with a simple pointer?

I tried but it cant. Can someone explain why?
Cant it be done with a simple pointer?

Under that va_X hood, I think it is done with pointers and pointer arithmetic.

Right so if I remember correctly, the actual parameters are passed on the stack... and the stack grows downward. You start from the address of the last named parameter and... subtract? Did you add to your pointer instead?
Then why does it even exist? Im really confused. This is what it says in my book:

You can define a function so that it allows any number of arguments to be passed to it. You
indicate that a variable number of arguments can be supplied by placing an ellipsis (which is three
periods, ...) at the end of the parameter list in the function definition. For example:

int sumValues(int first,...)
//Code for the function

There must be at least one ordinary parameter, but you can have more. The ellipsis must always be
placed at the end of the parameter list.
Obviously, there is no information about the type or number of arguments in the variable list, so
your code must figure out what is passed to the function when it is called. The C++ library defines va_start, va_arg, and va_end macros in the cstdarg header to help you do this. It’s easiest to
show how these are used with an example.

I dont get why you even need them and how does it make your life easier. Im really confused. Can anyone provide a better explanation?
Last edited on
Well, apart from the fact that my previous post may be completely, 100% wrong, you must keep portability in mind.

Portability basically means: the same code may be compiled differently to have the same effect on different machines.

You don't know how the va_X macros work under the hood, but all you need to do is use them as you're expected to use them, and they will work. If you'd write them yourself, your code may fail on machines which use... err different kinds of stacks or whatever.

Edit: minor correction.
Last edited on
Topic archived. No new replies allowed.