自我学习: C 标准库 - stdarg.h

xiaoxiao2021-02-28  46

自我学习: C 标准库 – <stdarg.h>

维基百科上对此标准库的介绍是

stdarg.h is a header in the C standard library of the C programming language that allows functions to accept an indefinite number of arguments.

翻译过来是该标准库能允许函数接受数量不定的参数(accept an indefinite number of arguments.).

It provides facilities for stepping through a list of function arguments of unknown number and type.

它提供了执行未知数量和类型的函数参数列表的工具。

在 cplusplus.com 上是这么解释的,感觉解释的很好。

This header defines macros to access the individual arguments of a list of unnamed arguments whose number and types are not known to the called function. A function may accept a varying number of additional arguments without corresponding parameter declarations by including a comma and three dots (,...) after its regular named parameters: return_type function_name ( parameter_declarations , ... ); To access these additional arguments the macros va_start, va_arg and va_end, declared in this header, can be used: First, va_start initializes the list of variable arguments as a va_list. Subsequent executions of va_arg yield the values of the additional arguments in the same order as passed to the function. Finally, va_end shall be executed before the function returns.

翻译过来是

该头文件定义一系列的宏来访问未命名参数列表的各个参数,这些参数的数量和类型是被调用函数所不知道的。 函数可以接受不同数量的附加参数,而不需要相应的参数声明,方法是在其常规命名参数之后加上逗号和三个点(,…): 返回类型 函数名(参数 , ...); 要访问这些附加的参数,可以使用在此库中声明的宏va_start、va_arg和va_end: 首先,va_start将变量参数列表初始化为一个va_list。 va_arg的后续执行产生附加参数的值,其顺序与传递给函数的顺序相同。 最后,在函数返回之前执行va_end。

怎么理解呢,直接看一个例子。

#include<stdarg.h> //该标准库导入. #include<stdio.h> //该函数计算(1, 2, 3)三个数的和 int sum(int number, ...){ //number为接受参数的数量,小数点表示接受不定量的参数. int temp = 1; va_list list_sum; //即声明一个储存不定量参数的容器,用来保存宏va_arg与宏va_end所需信息,类型为库变量va_list. va_start(list_sum, number); //库宏va_start,使va_list指向第一个参数va_arg. for(int i = 0; i < number; i++){ //执行循环,把(1,2,3)三个数依次与temp相加. temp += va_arg(list_sum, int); //库宏va_arg,在容器里检索参数,每次循环都返回不同的值. } va_end(list_sum); //库宏va_end,结束符,释放装有数据的容器va_list. return temp; } int main(){ printf("%d",sum(3, 1, 2, 3)); //第一个参数是number,表明了后面参数的数量,后三个参数即传入va_list的数值. return 0; }

对于萌新来说,一开始 sum() 的 三个小数点( ... )就无法理解了。

引入概念:可变参数函数

引用 Healtheon-博客园 的文章开头,地址:http://www.cnblogs.com/hanyonglu/archive/2011/05/07/2039916.html

在C中,当我们无法列出传递函数的所有实参的类型和数目时,可以用省略号指定参数表

void foo(...); void foo(parm_list,...);

这种方式和我们以前认识的不大一样,但我们要记住这是C中一种传参的形式,在后面我们就会用到它。

可变参数函数的参数数量是可变动的,它使用省略号来忽略之后的参数。例如printf函数一般。

printf函数的原型是 extern int printf(const char *format, ... );

就如同:

printf("hello,world!"); printf("%d %d", a, b); printf("%c,%c,%c,%c,%c", c, d, e, f, g);

引号后面的参数不一定需要,参数数目也不定。

stdarg.h 库成员

(图源 wiki百科)

(图源 百度百科)

ummmmmm,有事先放着,以后补充。

转载请注明原文地址: https://www.6miu.com/read-2626065.html

最新回复(0)