开发者

How would I use the `...` C operator to get a function to print out all it's args?

开发者 https://www.devze.com 2023-01-27 07:02 出处:网络
Here\'s what I tried... but failed: 开发者_StackOverflow中文版 void testfunc(...){ printf(...); } This will create a function that is equivalent to printf.Note that you cannot blindly print out argume

Here's what I tried... but failed:

开发者_StackOverflow中文版
void testfunc(...){
    printf(...);
}


This will create a function that is equivalent to printf. Note that you cannot blindly print out arguments, since you somehow need to know what type each argument is in advance. The format argument to printf informs it what arguments to expect and what types they will be.

#include <stdargs.h>

void testfunc(const char *format, ...)
{
    va_list ap;
    va_start(ap, format);

    vprintf(format, ap);

    va_end(ap);
}


You must use va_start(), va_end(), va_arg() and (not always) va_list and you must have at least one constant defined argument! For example:

#include <stdio.h>
#include <stdarg.h>

void PrintFloats ( int amount, ...)
{
  int i;
  double val;
  printf ("Floats passed: ");
  va_list vl;
  va_start(vl,amount);
  for (i=0;i<amount;i++)
  {
    val=va_arg(vl,double);
    printf ("\t%.2f",val);
  }
  va_end(vl);
  printf ("\n");
}

int main ()
{
  PrintFloats (3,3.14159,2.71828,1.41421);
  return 0;
}


You can use the va_start() and va_end() macros, but you'll have to have at least one argument:

void testfunc(int n, ...)
{
    va_list vl;
    va_start(vl, n); // initialize the va_list
    // something useful
    va_end(vl); // deinitializes vl
}

You can sequentially access the arguments with va_arg(vl, type) (e.g. int x = va_arg(vl, int)). Also, va_copy is occasionally useful if you want to copy the current state of the va_list

0

精彩评论

暂无评论...
验证码 换一张
取 消