Jump to content
  • Advertisement

Archived

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

KurtCPP

Functions with variable-length param lists.

This topic is 5325 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!