Optional arguments for functions
The C language allows you to define functions that have a variable number of arguments, called variadic functions. The Variadic function requires a fixed number of mandatory arguments, followed by a variable number of optional arguments.
This means that there must be at least one mandatory argument.
The number of variadic variable parameters is determined by the preceding mandatory arguments, or by a special value that defines the optional argument list.
The classic function is printf and scanf, both of which are extracted by formatting the string to extract the number of variable arguments.
Defined:
void Test (int count, ...)
When you write the Variadic function, you must define the argument pointer with the va_list type to access the optional arguments.
You can use the four macros in the Stdarg.h header file to handle the argument pointers.
void Va_start (Va_list argptr, Lastparam);
Call this macro to initialize before you begin using the optional argument.
Initializes the argptr pointer with the position of the first optional argument, and the second parameter is the last named parameter of the function.
void Va_arg (Va_list argptr, type);
Take an optional argument and move the pointer forward. Type is an independent variable that can just be read in.
void Va_end (Va_list argptr);
When you no longer need the argument pointer, call Va_end. If you use Va_start or va_copy to reinitialize a self-variable pointer, you must first call Va_end.
void Va_copy (va_list dest, va_list src);
Initializes the dest using the current src argument.
#include <stdio.h>#include<stdarg.h>//Optional argument function, Count is numbervoidArg_var (CharName[],intcount, ...) {printf ("name is:%s \ncount is:%d \ n", name, count); Va_list argptr; //defining an argument typeVa_start (Argptr, Count);//Initializing arguments for(intI=0; i<count; i++) {printf ("%s \ n", Va_arg (Argptr,Char*));//Value Printing} va_end (ARGPTR); //End Use}intMainintargcChar*argv[]) { //Call Arg_varArg_var ("Abeen",3,"Strarg1","strarg2","Strarg3");}
Optional arguments for the [ASM C/C + +] language functions