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


Unlimited Arguments (...)

Recommended Posts

IOFILE    122
Ok, I''ve never gotten around to learning it, simply because I''ve had no need to. But now, I''ve found a very good place in which I could use the unlimited arguments thingy, or whatever it''s called. I know the function would be declared as so: int Unlimited(int hi, ...) and now the programmer can enter in lots of ints. However, how do I find out how many params were sent through and how do I use each of them. Any help would be appreciated, as usual

Share this post

Link to post
Share on other sites
Quantum    122
usually, its used for string formatting
this is how you do it to have a formatted string like the printf()


#include <stdio.h> //needed for variable arguments

void *Something(const char *String, ...)
char Buffer[256]; //this holds the final string

va_list ArgList; //this is the argument list

va_start(ArgList, String); //begins processing the arguments

vsprintf(Buffer, String, ArgList); //print the string into Buffer

va_end(ArgList); //finished processing the arguments


its pretty simple actually

if you want it for something other than printing a formatted string into a buffer, then i cant help you, this is all i know about variable arguments

anyway, hope this helps

Share this post

Link to post
Share on other sites
arrogantgod    122
Here is the code for a simple routine I use to output debug information. You can use it like so:

FileDebug("Line %d, Error\n",iLine);

Here is the code:

void FileDebug( char *msg, ... )
FILE *fp;
va_list arglist;
char msgbuf[32768];

va_start( arglist, msg );
vsprintf( &msgbuf[0], msg, arglist );
va_end( arglist );

fp = fopen("debug.txt","a+");
fprintf( fp, msgbuf );
fclose( fp );

Look into the va_start family of functions. They are called variable-argument lists.

Hope that helps!

Share this post

Link to post
Share on other sites
byondo    122
Here is an example from the VC docs that I found to be helpful when researching this:

/* Returns the average of a variable list of integers. */
int average( int first, ... ){
int count = 0, sum = 0, i = first;
va_list marker;
va_start( marker, first ); /* Initialize variable arguments. [ie- tell the program the starting address] */
while( i != -1 ) {
sum += i;
i = va_arg( marker, int);
va_end( marker ); /* Reset variable arguments. */

return( sum ? (sum / count) : 0 );

Note that in this example they are assuming that the function will be terminated with a -1. So you would call it like:

All stdarg systems have to have some kind of terminator, because the va_arg function is just getting an address and incrementing it; it can''t infer how long your list is unless you tell it. Functions like printf() figure out the length of the list by parsing the initial string argument (ie- counting the number of
%d, etc markers).


Share this post

Link to post
Share on other sites