//给你举个MSDN上的例子 #include <stdio.h> #include <stdarg.h>// Declaration, but not definition, of ShowVar. int ShowVar( char *szTypes, ... );void 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 list // of n arguments, where n == strlen( szTypes ). void ShowVar( char *szTypes, ... ) { va_list vl; int i; // szTypes is the last argument specified; all // others must be accessed 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( "%i\n", Printable.i ); break; case 'f': Printable.f = va_arg( vl, float ); printf( "%f\n", Printable.f ); break; case 'c': Printable.c = va_arg( vl, char ); printf( "%c\n", Printable.c ); break; case 's': Printable.s = va_arg( vl, char * ); printf( "%s\n", Printable.s ); break; default: break; } } va_end( vl ); }
但我还想知道除了main()我还可以自己用c或者c++写出一个有参数列表的函数吗?
#include <stdio.h>
#include <stdarg.h>// Declaration, but not definition, of ShowVar.
int ShowVar( char *szTypes, ... );void 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 list
// of n arguments, where n == strlen( szTypes ).
void ShowVar( char *szTypes, ... )
{
va_list vl;
int i; // szTypes is the last argument specified; all
// others must be accessed 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( "%i\n", Printable.i );
break; case 'f':
Printable.f = va_arg( vl, float );
printf( "%f\n", Printable.f );
break; case 'c':
Printable.c = va_arg( vl, char );
printf( "%c\n", Printable.c );
break; case 's':
Printable.s = va_arg( vl, char * );
printf( "%s\n", Printable.s );
break; default:
break;
}
}
va_end( vl );
}