Archived

This topic is now archived and is closed to further replies.

KurtCPP

Functions with variable-length param lists.

Recommended Posts

KurtCPP    130
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

Share this post


Link to post
Share on other sites
MonkeyChuff    158
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);
}

Share this post


Link to post
Share on other sites
dragon___man    122
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?

Share this post


Link to post
Share on other sites