Is it possible to create a C or C++ function with a variable number of parameters?
Many thanks for your help.
Antonio.
_______
Printable View
Is it possible to create a C or C++ function with a variable number of parameters?
Many thanks for your help.
Antonio.
_______
Yes you can. This is an example I found in the VC++ Help :
int average(int first, ...)
{
int count = 0;
int sum = 0;
int i = first;
va_list marker;
va_start(marker, first);
while(i != -1)
{
sum += i;
count++;
i = va_arg(marker, int);
}
return (sum ? (sum / count) : 0 );
}
Other examples are the c-routines printf, sprintf, ...
Yes you can. This is an example I found in the VC++ Help :
int average(int first, ...)
{
int count = 0;
int sum = 0;
int 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 );
}
Other examples are the c-routines printf, sprintf, ...
Yes. Most C or C++ textbooks explains this technique. Alternately, do a search on "varargs.h" to get a rundown on how this is done.
Regards,
Paul McKenzie
You're forgetting the most important part: the header:
#include <varargs.h> for UNIX
#include <stdio.h>
#include <stdarg.h> for ANSI
Regards,
Paul McKenzie