How to use variable argument function
C supports the VA function. c ++ supports the VA function as an extension of C. It is not recommended in C ++, the polymorphism introduced by C ++ can also implement functions with variable parameter numbers. However, C ++'s overload function can only be a limited number of foreseeable parameters. In comparison, the VA function in C can define an infinite number of overload functions equivalent to C ++. In this regard, C ++ is powerless. The advantages of VA functions are convenience and ease of use, which can simplify the code. In order to unify the implementation on different hardware architectures and hardware platforms and increase code portability, the C compiler provides a series of macros to shield the differences caused by different hardware environments.
In ansi c, VA macros are defined in stdarg. H. They include va_list, va_start (), va_arg (), and va_end ().
Va_list arg_ptr: defines a pointer to a variable number of parameter lists;
Va_start (arg_ptr, argn): sets the parameter list pointer arg_ptr to the first optional parameter in the function parameter list. Description: argn is a fixed parameter located before the first optional parameter (or, the last fixed parameter ;... The order of parameters in the function parameter list in the memory is the same as that in the function declaration. If the declaration of a va function is void va_test (char a, char B, char C ,...), Then its fixed parameters are a, B, c in sequence, and the last fixed parameter argn is C, so it is va_start (arg_ptr, c ).
Va_arg (arg_ptr, type): return the parameter indicated by the pointer arg_ptr In the parameter list. The return type is type, and the pointer arg_ptr points to the next parameter in the parameter list.
Va_copy (DEST, Src): the types of DeST and SRC are va_list. va_copy () is used to copy the parameter list pointer and initialize DEST as SRC.
Va_end (arg_ptr): clears the parameter list. The parallel parameter pointer arg_ptr is invalid. Note: After the pointer arg_ptr is set to invalid, you can restore arg_ptr by calling va_start () and va_copy. Each time va_start ()/va_copy () is called, a corresponding va_end () must match it. The parameter pointer can be freely moved back and forth in the parameter list, but must be in va_start ()... Within va_end.