在C数目不详的参数功能 [英] Function with unknown number of parameters in C

查看:66
本文介绍了在C数目不详的参数功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能写(如果它是在所有可能的...)一个函数,它接受数目不详的C99参数(返回类型为常数)?

How can I write(if it's possible at all...) a function which takes unknown number of parameters in C99(the return type is constant)?

推荐答案

是的,你可以用什么作为可变参数的函数称为做在C。
基本的printf()和scanf()做到这一点。

Yes you can do it in C using what are referred to as Variadic Functions. The basic printf() and scanf() do this.

把省略号(三个点),它是你想要的参数变量数量是最后一个参数。

Put the ellipses (three dots) as the last parameter where you want the 'variable number of parameters to be.

要访问参数包括stdargs.h头:

To access the parameters include the stdargs.h header:

#include <stdarg.h>

然后你有一种特殊类型的的va_list 它给你传递的参数列表。

And then you have a special type va_list which gives you the list of arguments passed.

然后你可以使用的va_start 的va_arg va_end用来通过参数列表进行迭代。

Then you can use va_start, va_arg and va_end to iterate through the list of arguments.

例如:

#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;
}

一个完整的例子可以发现<一个href=\"http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_C.2C_Objective-C.2C_C.2B.2B.2C_and_D\">here

A full example can be found here

更新:新增count参数的例子,因为通常你需要一种方法来知道很多争论是如何通过。 printf()和scanf()函数通过格式字符串做,但一个简单的计数参数可以做到这一点。

UPDATE: Added the count parameter to the example since normally you would need a way to know how many arguments were passed. printf() and scanf() do it via the format string, but a simple count argument can do it too.

UPDATE2:打印整数变量列表中包括完整的例子

UPDATE2: Included full example of printing a variable list of integers.

这篇关于在C数目不详的参数功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆