Stdarg. H is the header file of C standard function library in C language. stdarg is simplified by standard (standard) arguments (parameters) to enable the function to receive variable parameters. The cstdarg header file of C ++ also provides this function. Although it is compatible with the header file of C, there are also conflicts.
The number of parameters of a Variable Parameter function can be changed. It uses ellipsis to ignore subsequent parameters. For example, the printf function in C is normal. Representative statement: int
Check (int A, double B ,...); variable Parameter functions must have at least one named parameter, so char * wrong (...); it is not allowed in C (such a statement is reasonable in C ++ ). In C, there must be a comma before omitting the symbol. In C ++, there is no such mandatory requirement.
The data type of stdarg. h: va_list is used to save the information required by the macro va_arg and macro va_end.
Stdarg. h macro: va_start points va_list to the starting Parameter
Va_arg
Search parameters
Va_end
Release va_list
Va_copy copy va_list content
To access an unnamed parameter, you must first declare a va_list variable in the Variable Parameter Function. Call va_start and pass in two parameters: the first parameter is a va_list type variable, and the second parameter is the name of the last parameter with a name before the ellipsis, then, the next parameter is returned for each call of va_arg. The first parameter of va_arg is va_list, and the second parameter is the type of the returned parameter. Finally, va_end must be called by va_list before the function is returned (va_list is treated as a parameter) (it is not required to read all parameters ). C99 provides an additional macro, va_copy, which can copy va_list. And va_copy (va2,
Va1) function is used to copy va1 to va2. There is no mechanism to define how to determine the parameter volume or data type passed to the function. Functions usually need to know or determine how they change. Common conventions include: Use a formatting string of the printf or scanf class to embed a specified type. The value (Sentinel) at the end of the Variable Parameter
Value ). Variable to specify the number of variable parameters.
Example:
# Include <stdio. h>
# Include <stdarg. h>
Void printargs (INT arg1,...) // output all int type parameters until-1 ends.
{
Va_list AP;
Int I;
Va_start (AP, arg1 );
For (I = arg1; I! =-1; I = va_arg (AP, INT ))
Printf ("% d", I );
Va_end (AP );
Putchar ('\ n ');
}
Int main (void)
{
Printargs (5, 2, 14, 84, 97, 15, 24, 48,-1 );
Printargs (84, 51,-1 );
Printargs (-1 );
Printargs (1,-1 );
Return 0;
}
This program generates output:
5 2 14 84 97 15 24 48
84 51
1