Recently I found function prototype with three dots argument. I wrote my own function and it compiled well:
void func(int a, ...){}
What does that mean?
update
Thank you guys! I figured it out. Here's my example:
void func(unsigned int n_args, int arg, ...)
{
for(unsigned int i = 0; i < n_args; ++i)
cout << *((int*)&arg + i) << ' ';
}
This function prints out arguments separated by space character.
A function with three dots means, that you can pass a variable number of arguments. Since the called function doesn't really know how many arguments were passed, you usually need some way to tell this. So some extra parameter would be needed which you can use to determine the arguments.
A good example would be printf
. You can pass any number of arguments, and the first argument is a string, which describes the extra parameters being passed in.
void func(int count, ...)
{
va_list args;
int i;
int sum = 0;
va_start(args, count);
for(i = 0; i < count; i++)
sum += va_arg(args, int);
va_end(ap);
printf("%d\n", sum);
}
update
To address your comment, you don't need the names of the arguments. That is the whole point of it, because you don't know at compile time which and how many arguments you will pass. That depends on the function of course. In my above example, I was assuming that only int
s are passed though. As you know from printf
, you pass any type, and you have to interpret them. that is the reason why you need a format specifier that tells the function what kind of parameter is passed. Or as shown in my example you can of course assume a specific type and use that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With