0

For example,a function that can take unlimited (or, more precisely, a very big number) amounts of the same type arguments, let's say integer, and then make all the passed integers have a value of 5.

What i ask is, can i,if i can,make a function with a non-fixed amount of parameters.

void setIntToFive(UNKNOWN AMOUNT OF INTS){
    //a for loop to assign a value to all the passed arguments
}

Then call it with different amounts of arguments every time

int a;
int b = 5;
setIntToFive(a,b);
int c;
setIntToFive(a,b,c);//Notice how i add another argument.

So, is there a way to make this, besides making the parameter an array.(i think it wouldn't work that way)

JorensM
  • 330
  • 4
  • 15

1 Answers1

2

You can use variable arguments.

Essentially

double average ( int num, ... )
{
    va_list arguments;
    double sum = 0;

    va_start ( arguments, num );
    for ( int x = 0; x < num; x++ )
    sum += va_arg ( arguments, double );
    va_end ( arguments );

    return sum / num;
}

va_list is a structure to hold all of the arguments passed in, and va_start assigns the arguments into that list. va_end cleans up the list after it is used. And num is the number of arguments being passed.

Check out the MSDN for more info.

Will Custode
  • 4,576
  • 3
  • 26
  • 51
  • That would, at a minimum, require him to pass pointers and to use some terminating argument or argument count. So you could make this work: `setIntToFive(&a, &b, nullptr);` or `setInToFive(&a, &b, &c, nullptr)`. – David Schwartz Sep 16 '13 at 19:57
  • No, variable arguments can be simpler. See my explanation. – Will Custode Sep 16 '13 at 19:59
  • So, after i pass the num, i can pass num more arguments to the function?When i call va_arg, does it return the next passed argument after int num? – JorensM Sep 16 '13 at 20:07
  • Yes, num indicates how many arguments take the place of the ... and va_arg returns the next argument in the list, of the specified type. I'll update with more links. – Will Custode Sep 16 '13 at 20:14