我常常看到一个声明如下的函数:
void Feeder(char *buff, ...)
“......”是什么意思?
答案 0 :(得分:27)
它允许可变数量的未指定类型的参数(如printf
)。
您必须使用va_start
,va_arg
和va_end
有关详细信息,请参阅http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html
答案 1 :(得分:18)
可变参数函数是可以采用可变数量参数的函数 并用省略号代替最后一个参数声明。 这种功能的一个例子是
printf
。典型的声明是
int check(int a, double b, ...);
Variadic函数必须至少有一个命名参数,例如
C中不允许char *wrong(...);
。
答案 2 :(得分:6)
这意味着正在声明variadic function。
答案 3 :(得分:6)
三个点'......'被称为省略号。在函数中使用它们使该函数成为可变参数函数。 在函数声明中使用它们意味着函数将在已定义的参数之后接受任意数量的参数。
例如:
Feeder("abc");
Feeder("abc", "def");
都是有效的函数调用,但以下不是:
Feeder();
答案 4 :(得分:3)
可变函数(多个参数)
#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;
}
答案 5 :(得分:0)
最后一个参数为...
的函数称为可变函数(Cppreference。2016)。 ...
用于允许使用不确定类型的可变长度参数。
当不确定参数的数量或类型时,可以使用可变参数函数。
可变参数功能示例: 让我们假设我们需要一个求和函数,该函数将返回可变数量的参数的总和。我们可以在这里使用可变参数函数。
#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;
}
输出:
练习题:在hackerrank practice problem here
中可以找到一个简单的练习可变参函数的问题。参考: