Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

C Variable parameters


May 11, 2021 C


Table of contents


C Variable parameters

Sometimes, you may encounter situations where you want a function to have a variable number of parameters instead of a predefined number of parameters. T he C language provides a solution to this situation by allowing you to define a function that can accept a variable number of parameters according to your specific needs. The following example demonstrates the definition of this function.

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

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

Note that the last argument of the function func() is written as an odd sign, i.e. three dots ... ) , the argument before the omitted sign is always int, which represents the total number of variable parameters to pass. T o use this feature, you need to use the stdarg.h header file, which provides functions and macros for implementing variable parameters. Here are the steps:

  • Defines a function, the last argument is an odd sign, and the argument preceding the elliption is always int, indicating the number of arguments.
  • Create a new type variable in va_list definition, which is defined in the stdarg.h header file.
  • Use int parameters and va_start macros to initialize the va_list variable is a list of parameters. The va_start is defined in the stdarg.h header file.
  • Use va_arg and va_list to access each item in the parameter list.
  • Use macro va_end to clean up the memory va_list to the variable.

Now let's follow the steps above to write a function with variable number of parameters and return their averages:

#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 results. I t should be noted that the function average() is called twice, each time the first argument represents the total number of variable parameters passed. The elliscient is used to pass a variable number of parameters.

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