Parsing of variable argument lists

variadic argument list comprehension

Function: Make the function accept any number of parameters with more than 1

Example: Find the average of several numbers

#include "stdio.h"

#include "windows.h"

#include "stdarg.h" //To be declared in the header file

int  average( int  n , ...) //n parameters

{

va_list  arg; //declare a variable arg of type va_list, at least one named parameter

int i = 0;

int  sum = 0;

va_start (arg, n ); //Start accessing parameters

for (i = 0; i < n; i++)

{

sum = sum + va_arg (arg, int ); //int is the next parameter type to be accessed

}

va_end (arg); //End access to parameters before completing the whole process

}

intmain  ()

{

int a = 1;

int b = 2;

int c = 3;

int d = 4;

int ret = average(2, 3, a, b);

printf("%d\n", ret);

system("pause");

return 0;

}

 

Note: 1. The first parameter of the va_start function is the variable of va_list, and the second is the number of variables

   2. va_arg needs to accept two parameters, one is the variable of va_list, and the other is the type of the next one to be accessed

   3. After the access is completed, va_end must be called.

   4. If the wrong type is specified in va_arg.

   5. The macro cannot determine the type of each parameter.

   

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326521594&siteId=291194637