Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function with three dots argument [duplicate]

Tags:

c++

function

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.

like image 734
Ivars Avatar asked Jan 03 '14 10:01

Ivars


1 Answers

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 ints 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.

like image 102
Devolus Avatar answered Oct 11 '22 20:10

Devolus