如何使用“...” (可变)参数? [英] How to use "..." (variable) argument?

查看:110
本文介绍了如何使用“...” (可变)参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我在 printf()函数中看到 ... 。完全HOW函数如 printf scanf 工作?

I've seen ... argument in printf() function. Exactly HOW functions like printf or scanf work? How is it that they can have infinite input values?

推荐答案

这依赖于C调用约定,即调用者弹出

This relies on the C calling convention, which is that the caller pops the arguments from the stack.

因为是调用者知道有多少个参数(以及它们的大小),它必须以某种方式将它传递给被调用者。使用printf()和family,这是通过格式字符串。对于execv和family,这通过一个终止NULL参数来指示。

Because it's the caller that knows how many arguments (and what size they are) it must communicate this to the callee in some manner. With printf() and family, this is via the format string. With execv and family, this is indicated by having a terminating NULL parameter.

被调用者使用标准头stdarg.h中定义的宏从堆栈中读取参数。

The callee reads the arguments from the stack using the macros defined in the standard header stdarg.h.

从内存(粗略),您需要定义一个类型为va_list的变量,它使用va_start从前面的参数初始化,如下所示:

From memory (sketchy), you need to define a variable of type va_list, which is initialised from the preceeding argument using va_start, as in:

void print(const char* format, ...)
{
  va_list args;

  va_start(args, format);


  /* read an int */
  int i = va_arg(args, int);

  /* read an char* */
  char* pc = va_arg(args, char*);


  va_end(args);
}

很明显,你必须解析格式字符串, ,或者一个char *,或者一个double,或者... ...

Obviously, you have to parse the format string to know whether to read an int, or a char*, or a double, or a ...

HTH

这篇关于如何使用“...” (可变)参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆