Latest web development tutorials

C variable parameter

Sometimes you may encounter such a situation, you want to function with variable number of arguments, rather than a predefined number of arguments. C language for this scenario provides a solution that allows you to define a function that can accept a variable number of parameters according to specific needs. The following example demonstrates the definition of such a function.

int func(int, ... ) 
{
   .
   .
   .
}

int main()
{
   func(1, 2, 3);
   func(1, 2, 3, 4);
}

Please note that the functionfunc () a final written arguments ellipsis that three dots (...),that argument before the ellipsis is alwaysint,representing the total number of variable parameters to be passed. To use this feature, you need to usestdarg.h header file that provides the functionality of variable parameters to achieve functions and macros.Specific steps are as follows:

  • The definition of a function, the last parameter is the ellipsis, ellipsis in front of the parameter is alwaysint, represents the number of parameters.
  • Create ava_list type variable in the function definition, this type is defined in the header file stdarg.h.
  • Int parameters and use macros va_startto initializeva_listvariable as a parameter list. Stdarg.h va_start macro is defined in the header file.
  • Useva_arg macros and va_listvariables to access the list of parameters for each item.
  • Use a macro to cleanva_end given va_listvariable memory.

Let us now follow the steps above to write functions with a variable number of arguments and returns their average:

#include <stdio.h>
#include <stdarg.h>

double average(int num,...)
{

    va_list valist;
    double sum = 0.0;
    int i;

    /* 为 num 个参数初始化 valist */
    va_start(valist, num);

    /* 访问所有赋给 valist 的参数 */
    for (i = 0; i < num; i++)
    {
       sum += va_arg(valist, int);
    }
    /* 清理为 valist 保留的内存 */
    va_end(valist);

    return sum/num;
}

int main()
{
   printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));
   printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));
}

When the above code is compiled and executed, it produces the following result. It should be noted that the functionaverage () is called twice, each time the first parameter represents the total number are transferred variable parameters.Ellipses are used to deliver a variable number of arguments.

Average of 2, 3, 4, 5 = 3.500000
Average of 5, 10, 15 = 10.000000