ala*_*amh 35 c parameters syntax function
我常常看到一个声明如下的函数:
void Feeder(char *buff, ...)
Run Code Online (Sandbox Code Playgroud)
这是什么意思?
kni*_*ttl 31
它允许可变数量的未指定类型的参数(如同printf).
你有访问它们va_start,va_arg并va_end
有关详细信息,请参阅http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html
N 1*_*1.1 19
变量函数是可以采用可变数量的参数的函数,并使用省略号代替最后一个参数进行声明.这种功能的一个例子是
printf.典型的声明是
Run Code Online (Sandbox Code Playgroud)int check(int a, double b, ...);变量函数必须至少有一个命名参数,例如,
Run Code Online (Sandbox Code Playgroud)char *wrong(...);是不允许在C.
最后一个参数的函数...称为可变函数(Cppreference.2016)。这...用于允许具有未指定类型的可变长度参数。
当我们不确定参数的数量或其类型时,我们可以使用可变参数函数。
可变参数函数的示例: 假设我们需要一个 sum 函数,它将返回可变数量参数的总和。我们可以在这里使用可变参数函数。
#include <stdio.h>
#include <stdarg.h>
int sum(int count, ...)
{
int total, i, temp;
total = 0;
va_list args;
va_start(args, count);
for(i=0; i<count; i++)
{
temp = va_arg(args, int);
total += temp;
}
va_end(args);
return total;
}
int main()
{
int numbers[3] = {5, 10, 15};
// Get summation of all variables of the array
int sum_of_numbers = sum(3, numbers[0], numbers[1], numbers[2]);
printf("Sum of the array %d\n", sum_of_numbers);
// Get summation of last two numbers of the array
int partial_sum_of_numbers = sum(2, numbers[1], numbers[2]);
printf("Sum of the last two numbers of the array %d\n", partial_sum_of_numbers);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
练习题:练习可变参数函数的简单问题可以在hackerrank 练习题中找到
参考:
三个点'......'被称为省略号.在函数中使用它们使该函数成为可变函数.在函数声明中使用它们意味着函数将在已定义的参数之后接受任意数量的参数.
例如:
Feeder("abc");
Feeder("abc", "def");
Run Code Online (Sandbox Code Playgroud)
都是有效的函数调用,但以下不是:
Feeder();
Run Code Online (Sandbox Code Playgroud)
可变参数函数(多参数)
#include <stdarg.h>
double average(int count, ...)
{
va_list ap;
int j;
double tot = 0;
va_start(ap, count); //Requires the last fixed parameter (to get the address)
for(j=0; j<count; j++)
tot+=va_arg(ap, double); //Requires the type to cast to. Increments ap to the next argument.
va_end(ap);
return tot/count;
}
Run Code Online (Sandbox Code Playgroud)