Advertisement

Variable length parameter lists

Started by March 09, 2001 11:56 PM
1 comment, last by granat 23 years, 11 months ago
I know how to declare: MyFunc(int a, ...) If I called this function like this: int x=10; int y=8; MyFunc(x, y); How can I obtain the value for y inside the function?
-------------Ban KalvinB !
An example from the MSDN:
  int average( int first, ... ){   int count = 0, sum = 0, i = first;   va_list marker;   va_start( marker, first );     /* Initialize variable arguments. */   while( i != -1 )   {      sum += i;      count++;      i = va_arg( marker, int);   }   va_end( marker );              /* Reset variable arguments.      */   return( sum ? (sum / count) : 0 );}  

Basically, make a va_list, call va_start and pass it the list name and the name of the variable(in your case ''a''), and then call va_arg until it returns -1. Then call va_end to finish up.
Advertisement
Worth noting is that it returns -1 because that is the last parameter passed, i.e. Average(1,2,3,4,-1). You also have to be able to determine the type of the arguements. With printf that is done by the format string.
Keys to success: Ability, ambition and opportunity.

This topic is closed to new replies.

Advertisement