This is not a very big subject really, it's give things we will look @ in this article. I will list them below, with an description below.
- ...
- va_list
- va_start
- va_arg
- va_end
...
This is what you put in your function declaration, if you have seen printf it looks like this:
int printf(const char *, ...);
The ... show where the dynamic arguments begins, it can never be first and it can never be static arguments after it, you will understand why later.
va_list
The control handle for the arguments, on most systems it's a void *, but some tend to still hold on to char * for some reason.
control handle is not correct acually, it is the memory address that the argument is in, I will explain this more in va_start, you make one like this(rather obvious).
va_list va; /* Replace va with your name */
va_start
This in a macro, so no prototype can be shown. But this is how you could use it for example:
void a(char b, ...) {
va_list va;
va_start(va, b);
}
What va_start really does it that is takes the memory address of b(argument 2) and place it in va_list, hence it's a void *. That means the second argument should be the argument before the dynamic arguments begins.
va_arg
Just like va_start this is a macro, this one is a simple one just now, I really want to show you a prototype, but im afraid that's rather impossible. But here is an code example.
void a(char b, ...) {
char c;
va_list va;
va_start(va, b);
c = va_arg(va, char); }
The first argument is just like va_start the memory address, the second is how much memory it should move, if you would place int there is would be four, it also "return"(hence it's a macro) that memory.
va_end
I havn't acually checked what this acually does, but it probably free the memory, you use it like this:
void a(char b, ...) {
char c;
va_list va;
va_start(va, b);
c = va_arg(va, char);
va_end(va); }
One single argument, as simple as anything.
Example
Here is little function that I made up for example, I just coded it out of thin air while writing this article so excuse any misbehaviour.
#include <stdarg.h> /* I don't think I said it but here is it declared. */
#include <stdio.h>
void print(char *one, ...) {
va_list va;
char *p;
for(p = one; p; p = va_arg(va, char *))
puts(p);
va_end(va);
return; }
I hope that all works ok, otherwise it could be very embarassing. |