Variable number of parameters... C/C++ vs C#

A friend and I were talking about variable length parameter lists in C/C++ the other day and neither of us knew how to do it. We knew there must be some way because of the printf function. Just out of curiosity I did some googling and figured out how to do it.

Just incase you have the same curiosity here is a sample from this MSDN article on how to do it (NOTE that this C/C++ code was taken straight from the article I just included it here for comparison purposes)

int average( int first, ... )
{
   int count = 0, sum = 0, i = first;
   va_list marker;

   va_start( marker, first );
   while( i != -1 )
   {
      sum += i;
      count++;
      i = va_arg( marker, int);
   }
   va_end( marker );
   return( sum ? (sum / count) : 0 );
}

So in order to write a function in C/C++ that accepts a variable number of parameters you need to do the following:

  • Have at least one required parameter
  • Use "..." to signify a variable number of parameters
  • Use va_start, va_arg, and va_end to interact with the parameters
  • When calling this function you will need to pass in a flag/sentinel to signify the end of the variable list

Just for comparsion here is a function that does the same thing in C#

int Average(params int[] ints)
{
    int total = 0;
    foreach(int i in ints)
        total += i;
    return (ints.Length > 0 ? total / ints.Length : 0);
}

So to do this in C# you just use the keyword params in front of an array parameter and you get a variable number of parameters.

3 Comments

  • The difference being that you can supply various datatypes in the c/c++ version but only the int datatype in your c# example. I suppose you could always extend the c# version by declaring the parameter to be



    int something(params object[] vals)

  • Why is first passed into va_start?
    What exactly are the roles of the parameters in this function?

  • va_start's first parameter is a variable which is used to keep track of the va_arg process.

    va_start's second parameter is the name of the last "fixed" parameter (the parameter before the "...").

Comments have been disabled for this content.