• Welcome to Computer Association of SIUE - Forums.
 

Functions with Variable Argument Lists

Started by Justin Camerer, 2006-09-23T15:19:45-05:00 (Saturday)

Previous topic - Next topic

Justin Camerer

I'm working on a program where I am trying to create a fuction with a variable argument list, such as printf(). I have been looking into these and every example I find needs to have at one static parameter, like a format string.

Does anyone know how to create a function with a variable argument list?
Justin Camerer
Do yo' chain hang low?

William Grim

I've used them.  They don't need a static parameter, but I know what you are trying to say.  They always need a format parameter or the va_* macros don't know how to determine the types of the parameters.  va_* functionality is built into GCC and likely other compilers, and they need internal support to work.  I have a feeling the internal compiler functions just parse the format string at compile time and generate the types required.

Anyway, this is how you create a function with variable arguments:

void doStuff(const char *fmt, ...);

Look at the man pages on va_start, va_end, va_arg, and va_copy.
William Grim
IT Associate, Morgan Stanley

Justin Camerer

Any ideas on variable length argument lists where they are all of the same type?
Basically, i want to be able to pass an array to a function, like so:

void do_schtuff( 1.0f, 2.0f, 3.0f );
or
void do_schtuff( { 1.0f, 2.0f, 3.0f } );

without having to declare an array first and pass it like so:


float schtuff[] = { 1.0f, 2.0f, 3.0f };
void do_schtuff( schtuff );


Any ideas? or am i just lazy?
Justin Camerer
Do yo' chain hang low?

William Grim

This works:


#include

void DoStuff(float vals[], size_t valsLen)
{
  for (size_t i=0; i    printf("%.2f ", vals[i]);
  }
  printf("\n");
}

int main()
{
  DoStuff((float[]){1.098,2.0},2);
  return 0;
}


However, as you can see, a cast is done.  It's best to try and avoid casts, because the compiler will just assume you are correct.  I think you should just declare the array on the stack before calling the function.  With the existing code, if the interface to the function is ever changed, your code will probably break.
William Grim
IT Associate, Morgan Stanley