Newbie
Newbie

Reputation: 1613

C++ How to loop dynamic arguments from function?

I need to loop all the dynamic arguments i have gave to my function, how?

I mean this kind of code:

void something(int setting1, int setting2, ...){
   // loop somehow all the ... arguments and use setting1-2 values in that loop
}

setting1 and setting2 are not part of the dynamic argument list.

Upvotes: 1

Views: 3038

Answers (4)

Dmitry
Dmitry

Reputation: 6780

This MSDN article contains an explanation and a reasonable example.

Note: the whole va_arg business is not very safe, and as others suggested if all of those arguments are of the same type, just put them all in a container and pass that instead.

e.g:

void func(int arg1, int arg2, std::vector<float> &myFloats)
{
    // myFloats can be used here, and you know how many floats there are
    // by calling myFloats.size()
} 

Upvotes: 1

nhaa123
nhaa123

Reputation: 9808

Like this:


#include <stdarg.h>

void Foo(int s1, int count, ...)
{
        va_list args;

        va_start(args, count);

        if (count > 0) {
            // Do something with the first variable, assuming it's std::string...
            std::string v1(va_arg(args, std::string));

            for (unsigned int i = 0; i < count - 1; ++i)
                    std::cout << va_arg(args, std::string) << "|";
        }

        va_end(args);
}

Upvotes: 1

plinth
plinth

Reputation: 49199

Use va_ functions. Here's an example:

void PrintFloats ( int amount, ...)
{
    int i;
    double val;
    printf ("Floats passed: ");
    va_list vl;
    va_start(vl,amount);
    for (i=0;i<amount;i++)
    {
        val=va_arg(vl,double);
        printf ("\t%.2f",val);
    }
    va_end(vl);
    printf ("\n");
}

Your other arguments have to indicate how many other args there are. printf, for example, uses the percents in the format string to do this. My example uses the first arg.

And lest you think that this type of argument passing is the bees knees, be sure to read varargs are bad, m'kay.

Upvotes: 4

Justin Ethier
Justin Ethier

Reputation: 134255

You could extract the variable arguments into a data structure (list, array, etc) and add setting1 / setting2 to that structure as well.

Then just loop over all of the structure's elements :)

Upvotes: 0

Related Questions