包含变量参数列表的函数

变量参数列表中所述,使用参数列表中的省略号 (...) 来声明需要变量列表的函数。 使用在 STDARG.H 包含文件中描述的类型与宏来访问变量列表所传递的参数。 有关这些宏的详细信息,请参阅 C 运行库的文档中的 va_arg、va_end、va_start

示例

以下示例说明如何将 va_startva_argva_end 宏与 va_list 类型一起使用(在 STDARG.H 中声明):

// variable_argument_lists.cpp
#include <stdio.h>
#include <stdarg.h>

//  Declaration, but not definition, of ShowVar.
void ShowVar( char *szTypes, ... );
int main() {
   ShowVar( "fcsi", 32.4f, 'a', "Test string", 4 );
}

//  ShowVar takes a format string of the form
//   "ifcs", where each character specifies the
//   type of the argument in that position.
//
//  i = int
//  f = float
//  c = char
//  s = string (char *)
//
//  Following the format specification is a variable 
//  list of arguments. Each argument corresponds to 
//  a format character in the format string to which 
// the szTypes parameter points 
void ShowVar( char *szTypes, ... ) {
   va_list vl;
   int i;

   //  szTypes is the last argument specified; you must access 
   //  all others using the variable-argument macros.
   va_start( vl, szTypes );

   // Step through the list.
   for( i = 0; szTypes[i] != '\0'; ++i ) {
      union Printable_t {
         int     i;
         float   f;
         char    c;
         char   *s;
      } Printable;

      switch( szTypes[i] ) {   // Type to expect.
         case 'i':
            Printable.i = va_arg( vl, int );
            printf_s( "%i\n", Printable.i );
         break;

         case 'f':
             Printable.f = va_arg( vl, double );
             printf_s( "%f\n", Printable.f );
         break;

         case 'c':
             Printable.c = va_arg( vl, char );
             printf_s( "%c\n", Printable.c );
         break;

         case 's':
             Printable.s = va_arg( vl, char * );
             printf_s( "%s\n", Printable.s );
         break;

         default:
         break;
      }
   }
   va_end( vl );
}
  

注释

上一个示例演示以下重要概念:

  • 在访问任何变量参数前,必须建立一个列表标记作为类型 va_list 的变量。 在前面的示例中,该标记称为 vl。

  • 使用 va_arg 宏访问各个参数。 必须告知 va_arg 宏要检索的参数的类型,以便它可以从堆栈中传输正确的字节数。 如果为 va_arg 指定的大小的类型与通过调用程序提供的类型不同,则结果是不可预知的。

  • 应将使用 va_arg 宏获取的结果显式强制转换为所需类型。

  • 必须调用 va_end 宏以终止可变参数处理。

请参见

参考

C++ 函数定义