Functions with variable-length param lists.

Started by
3 comments, last by KurtCPP 20 years, 5 months ago
HI everyone. Could someone explain to someone else (ie me) how I can declare a function that gets a list of parameters which size is variable (like printf() or lie a function that would calculate the average of its parameters e.g). Thanks for your help. Prog, Hex & Rock''n''Roll : I don''t like the Prog but the Prog likes me. Some nice poetry to sweeten your spirit and relax a bit before programming
Prog, Games & Rock'n'Roll :I don't like the Prog but the Prog likes me.
Advertisement
http://search.yahoo.com/search?ei=UTF-8&fr=fp-top&p=variable+argument+list+functions+c%2B%2B
Abnormal behavior of abnormal brain makes me normal...
You can do it by declaring a function thus;

int Average (int iStart, ...);

So...

#include <stdarg.h>#include <stdio.h>int Average (int iStart, ...);void main(){   printf("Average is: %d\n", Average(10,11,12,13,14,15,16,-1);}int Average(int iStart, ...){   int i = iStart;   int iSum = 0;   int iCount = 0;   va_list oArgs;   va_start(oArgs, iStart);   while (i != -1)   {      iSum += i;      iCount++;      i = va_arg(oArgs, int);   }   va_end(oArgs);   return (iSum ? (iSum / iCount) : 0);}
How would you take these parameters and pass them to printf, sprintf, or fprintf?

as in:
int Average (int iStart, ...);

how would you go about doing:

int Average (int iStart, ...)
{
fprintf(someFile, I don''t know the rest
}

also, isn''t iStart supposed to be a pointer?
Check out vsprintf for the va_args version of sprintf.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

This topic is closed to new replies.

Advertisement