1

Possible Duplicate:
What does … mean in an argument list in C ?

I was reading a book about win32 programming and i saw a function like this:

   int CDECL MessageBoxprintf(TCHAR *szCaption,TCHAR *szFrmat,...)  
   {
       TCHAR szBuffer[1024];
       va_list pArgList;
       va_start (pArgList,szFrmat);
      _vsnprintf(szBuffer,sizeof(szBuffer)/sizeof(TCHAR),szFrmat,pArgList);
       va_end (pArgList);
       return MessageBox(NULL,szBuffer,szCaption,0);
    }

what does ,... means in the parameters of a function?

I tried to find answers with searching but i got nothing useful.

Community
  • 1
  • 1
Zoli
  • 588
  • 2
  • 8
  • 13

4 Answers4

3

These are called variadic functions.

... at the end of the parameter list means that the function will take an indeterminate amount of arguments after the last required argument (if any).

The excess arguments can be of any type. For example:

void f(...) {}

f( 5, 0, 24 ); // works

f( "", 5, false ); // works

f( true, false, 4 ); // works

And that's very nifty. And it is common that we want them to be of any type but at the same time we might want to do some generic thing with them. For that we use templates:

template <typename...Type> Type f( Type ... type ) {

    // do some generic thing        

    f(type...); // move to next argument
}
David G
  • 94,763
  • 41
  • 167
  • 253
3

It means you can have varible numbers of arguments to that function instead of a fixed number of arguments. A perfect usecase would be

For example Lets say we have a function called average

double average ( int num, ... )
{
  va_list arguments;                     // A place to store the list of arguments
  double sum = 0;

  va_start ( arguments, num );           // Initializing arguments to store all values after num
  for ( int x = 0; x < num; x++ )        // Loop until all numbers are added
    sum += va_arg ( arguments, double ); // Adds the next value in argument list to sum.
  va_end ( arguments );                  // Cleans up the list

  return sum / num;                      // Returns the average
}

you can call this function like this with any number of arguments

cout<< average ( 3, 12.2, 22.3, 4.5 ) <<endl; 

Also the arguments passed don't have to be of the same type. For more information look at this link

anijhaw
  • 8,954
  • 7
  • 35
  • 36
1

Usually it's an error if you pass too many arguments to a function, but with ... you can pass more arguments to it. It has a variable cout of arguments. The arguments passed to the function can retrieved by the macros in stdarg.h. See this for more information.

qwertz
  • 14,614
  • 10
  • 34
  • 46
0

It means that the func can accept variable number of arguments (which are later parsed by va* macros)

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85