共用方式為


具有變數引數清單的函式

需要變數清單的函式會使用宣告的引數清單中的省略符號 ([...]) 中所述變數引數清單。 使用型別和 STDARG 所述的巨集。H 包含存取傳遞引數,是由變數的清單中的檔案。 如需有關這些巨集的詳細資訊,請參閱 va_arg、 va_end、 va_start C Run-time 程式庫的文件中。

範例

下列範例所示如何va_startva_arg,以及va_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 + + 函式定義