41

How I can have variable number of parameters in my function in C++.

Analog in C#:

public void Foo(params int[] a) {
    for (int i = 0; i < a.Length; i++)
        Console.WriteLine(a[i]);
}

public void UseFoo() {
    Foo();
    Foo(1);
    Foo(1, 2);
}

Analog in Java:

public void Foo(int... a) {
    for (int i = 0; i < a.length; i++)
        System.out.println(a[i]);
}

public void UseFoo() {
    Foo();
    Foo(1);
    Foo(2);
}
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
AndreyAkinshin
  • 18,603
  • 29
  • 96
  • 155
  • 8
    As others have pointed out, a variadic function is specifically what you're looking for. But unless you plan on sending a mix of types to the function, you're better off just passing a pointer or reference to a vector containing your parameters instead. – Richard Simões Oct 16 '09 at 18:51

8 Answers8

52

These are called Variadic functions. Wikipedia lists example code for C++.

To portably implement variadic functions in the C programming language, the standard stdarg.h header file should be used. The older varargs.h header has been deprecated in favor of stdarg.h. In C++, the header file cstdarg should be used.

To create a variadic function, an ellipsis (...) must be placed at the end of a parameter list. Inside the body of the function, a variable of type va_list must be defined. Then the macros va_start(va_list, last fixed param), va_arg(va_list, cast type), va_end(va_list) can be used. For example:

#include <stdarg.h>

double average(int count, ...)
{
    va_list ap;
    int j;
    double tot = 0;
    va_start(ap, count); //Requires the last fixed parameter (to get the address)
    for(j=0; j<count; j++)
        tot+=va_arg(ap, double); //Requires the type to cast to. Increments ap to the next argument.
    va_end(ap);
    return tot/count;
}
Stephan202
  • 59,965
  • 13
  • 127
  • 133
  • 1
    I think that example is C.. but close enough. – Licky Lindsay Oct 16 '09 at 18:48
  • C usually compiles fine in C++ compilers. – Carl Norum Oct 16 '09 at 18:48
  • I assume it compiles but the use of header instead of flags it as clearly "C". – Licky Lindsay Oct 16 '09 at 18:55
  • 2
    @Licky: as stated, I copied the code from Wikipedia. And I highlighted the remark that for C++ the `cstdarg` header should be used. Seems clear to me. – Stephan202 Oct 16 '09 at 18:59
  • If you use cstdarg, won't that leave va_list etc. in the std namespace? Or are those macros in cstdarg? – David Thornley Oct 16 '09 at 19:08
  • @Stephan202 my first reply must have been before you copied the example and added the highlighting. – Licky Lindsay Oct 16 '09 at 19:09
  • FWIW - I always use the old C-style header names even in C++. The new names still feel foreign and they provide no value. I'm not the only one: http://blogs.msdn.com/vcblog/archive/2008/08/28/the-mallocator.aspx#8904359 – Michael Burr Oct 16 '09 at 19:12
  • @David Thornley - `va_list` is a type. Most everything else in cstdarg/stdarg.h are macros. – Michael Burr Oct 16 '09 at 19:14
  • Oh - and the cstdarg might put `va_list` in the global namespace. It has to put it in the `std` namespace, but is allowed to also put it in the global namespace (a big reason why the C++ specific headers really provide no value). – Michael Burr Oct 16 '09 at 19:16
  • On one very important thing that should be added to the answer here is that the types of things that may be passed in the varargs part of the parameter list is severely limited - basically only built in types, enumerations, pointers, and POD types. – Michael Burr Oct 16 '09 at 19:21
  • @Michael: feel free to edit the answer! It sounds like you know more about this subject than me. – Stephan202 Oct 16 '09 at 19:29
  • Re: C headers in C++. Don't C++ versions clean up some namespace pollution (undefining macros) and declare additional overloads. E.g `` should be very different from ``? – UncleBens Oct 16 '09 at 21:38
  • variadic templates is definitely the C++ way, but after writing the code for making a simple printf() wrapper, I'll stick with cstdarg just because it works, it's standards compliant, and it is readable enough for me not to have to google what that code does in 6 months. Gosh, take pity of the poor soul that will maintain your code in the future... – DanyAlejandro May 03 '19 at 16:25
21

The real C++ solution is variadic templates. You'll need a fairly recent compiler and enable C++11 support if needed.

Two ways to handle the "do the same thing with all function arguments" problem: recursively, and with an ugly (but very very Standards compliant) solution.

The recursive solution looks somewhat like this:

template<typename... ArgTypes>
void print(ArgTypes... args);
template<typename T, typename... ArgTypes>
void print(T t, ArgTypes... args)
{
  std::cout << t;
  print(args...);
}
template<> void print() {} // end recursion

It generates one symbol for each collection of arguments, and then one for each step into the recursion. This is suboptimal to say the least, so the awesome C++ people here at SO thought of a great trick abusing the side effect of a list initialization:

struct expand_type {
  template<typename... T>
  expand_type(T&&...) {}
};
template<typename... ArgTypes>
void print(ArgTypes... args)
{ 
  expand_type{ 0, (std::cout << args, 0)... };
}

Code isn't generated for a million slightly different template instantiations, and as a bonus, you get preserved order of you function arguments. See the other answer for the nitty gritty details of this solution.

Community
  • 1
  • 1
rubenvb
  • 74,642
  • 33
  • 187
  • 332
17

In C++11 and later you can also use initializer lists.

int sum(const initializer_list<int> &il)
{
    int nSum = 0;
    for (auto x: il) 
        nSum += x;
    return nsum;
}

cout << sum( { 3, 4, 6, 9 } );
Seb
  • 839
  • 8
  • 13
6

Aside from the other answers, if you're just trying to pass an array of integers, why not:

void func(const std::vector<int>& p)
{
    // ...
}

std::vector<int> params;
params.push_back(1);
params.push_back(2);
params.push_back(3);

func(params);

You can't call it in parameter, form, though. You'd have to use any of the variadic function listed in your answers. C++0x will allow variadic templates, which will make it type-safe, but for now it's basically memory and casting.

You could emulate some sort of variadic parameter->vector thing:

// would also want to allow specifying the allocator, for completeness
template <typename T> 
std::vector<T> gen_vec(void)
{
    std::vector<T> result(0);
    return result;
}

template <typename T> 
std::vector<T> gen_vec(T a1)
{
    std::vector<T> result(1);

    result.push_back(a1);

    return result;
}

template <typename T> 
std::vector<T> gen_vec(T a1, T a2)
{
    std::vector<T> result(1);

    result.push_back(a1);
    result.push_back(a2);

    return result;
}

template <typename T> 
std::vector<T> gen_vec(T a1, T a2, T a3)
{
    std::vector<T> result(1);

    result.push_back(a1);
    result.push_back(a2);
    result.push_back(a3);

    return result;
}

// and so on, boost stops at nine by default for their variadic templates

Usage:

func(gen_vec(1,2,3));
GManNickG
  • 494,350
  • 52
  • 494
  • 543
3

See Variadic functions in C, Objective-C, C++, and D

You need to include stdarg.h and then use va_list, va_start, va_arg and va_end, as the example in the Wikipedia article shows. It's a bit more cumbersome than in Java or C#, because C and C++ have only limited built-in support for varargs.

Jesper
  • 202,709
  • 46
  • 318
  • 350
1

If you don't care about portability, you could port this C99 code to C++ using gcc's statement expressions:

#include <cstdio>

int _sum(size_t count, int values[])
{
    int s = 0;
    while(count--) s += values[count];
    return s;
}

#define sum(...) ({ \
    int _sum_args[] = { __VA_ARGS__ }; \
    _sum(sizeof _sum_args / sizeof *_sum_args, _sum_args); \
})

int main(void)
{
    std::printf("%i", sum(1, 2, 3));
}

You could do something similar with C++0x' lambda expressions, but the gcc version I'm using (4.4.0) doesn't support them.

Community
  • 1
  • 1
Christoph
  • 164,997
  • 36
  • 182
  • 240
1

GManNickG and Christoph answers are good, but variadic functions allow you push in the ... parameter whatever you want, not only integers. If you will want in the future, to push many variables and values of different types into a function without using variadic function, because it is too difficult or too complicated for you, or you don't like the way to use it or you don't want to include the required headers to use it, then you always can use void** parameter.

For example, Stephan202 posted:

double average(int count, ...)
{
    va_list ap;
    int j;
    double tot = 0;
    va_start(ap, count); //Requires the last fixed parameter (to get the address)
    for(j=0; j<count; j++)
        tot+=va_arg(ap, double); //Requires the type to cast to. Increments ap to the next argument.
    va_end(ap);
    return tot/count;
}

this can be also written as:

double average(int count, void** params)
{
    int j;
    double tot = 0;
    for (j=0; j<count; j++)
       tot+=*(double*)params[j];
    return tot/count;
}

Now use it like this way:

int _tmain(int argc, _TCHAR* argv[])
{
    void** params = new void*[3];
    double p1 = 1, p2 = 2, p3 = 3;
    params[0] = &p1;
    params[1] = &p2;
    params[2] = &p3;
    printf("Average is: %g\n", average(3, params));
    system("pause");
    return 0;
}

for full code:

#include "stdafx"
#include <process.h>

double average(int count, void** params)
{
    int j;
    double tot = 0;
    for (j=0; j<count; j++)
        tot+=*(double*)params[j];
    return tot/count;
}

int _tmain(int argc, _TCHAR* argv[])
{
    void** params = new void*[3];
    double p1 = 1, p2 = 2, p3 = 3;
    params[0] = &p1;
    params[1] = &p2;
    params[2] = &p3;
    printf("Average is: %g\n", average(3, params));
    system("pause");
    return 0;
 }

OUTPUT:

Average is: 2

Press any key to continue . . .

0

I do mine like this in c++ builder xe.xx:

String s[] = {"hello ", " unli", " param", " test"};
String ret = BuildList(s, 4);

String BuildList(String s[], int count)
{
    for(int i = 0; i < count; i++)
    {
        //.... loop here up to last s[i] item ... 
    }
}
HMD
  • 2,202
  • 6
  • 24
  • 37
a_asiado
  • 9
  • 1
  • 1
    Please check [how to answer](https://stackoverflow.com/help/how-to-answer) and also use formatting tools to indent code – Morse Apr 16 '18 at 02:56