Skip to main content
gamedev.net
🔒 Locked

Functions with variable-length param lists.

Started by KurtCPP 3 replies 1.8k views
Original Post
KurtCPP
KurtCPP
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.
original vesoljc
original vesoljc
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...
MonkeyChuff
MonkeyChuff
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);
}
dragon___man
dragon___man
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?
Paradigm Shifter
Paradigm Shifter
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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.