是的,您可以使用所谓的可变函数在 C 中完成此操作。
标准printf() http://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html and scanf() http://pubs.opengroup.org/onlinepubs/9699919799/functions/scanf.html例如,函数可以执行此操作。
将省略号(三个点)作为您希望“可变数量的参数”所在的最后一个参数。
要访问参数包括<stdarg.h>
header:
#include <stdarg.h>
然后你就有了一个特殊的类型va_list
它为您提供了传递的参数列表,您可以使用va_start
, va_arg
and va_end
宏来迭代参数列表。
例如:
#include <stdarg.h>
int myfunc(int count, ...)
{
va_list list;
int j = 0;
va_start(list, count);
for(j=0; j<count; j++)
{
printf("%d", va_arg(list, int));
}
va_end(list);
return count;
}
调用示例:
myfunc(4, -9, 12, 43, 217);
完整的示例可以在以下位置找到:维基百科 http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_C.2C_Objective-C.2C_C.2B.2B.2C_and_D.
The count
示例中的参数告诉被调用函数传递了多少个参数。这printf()
and scanf()
通过格式字符串找到它,但是一个简单的count
论证也能做到这一点。有时,代码使用标记值,例如负整数或空指针(请参阅execl() http://pubs.opengroup.org/onlinepubs/9699919799/functions/execl.html例如)。