va_arg
来自cppreference.com
|
|
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
| 在头文件 <cstdarg> 中定义
|
||
| T va_arg(va_list ap, T); |
||
va_arg宏扩展到对应到下一个参数的类型T表达va_listap.原文:
The
va_arg macro expands to an expression of type T that corresponds to the next parameter from the va_list ap.在此之前调用
va_arg,ap必须通过调用初始化为va_start或va_copy,而没有中间调用va_end。每一次调用的va_arg宏修改ap指向下一个变量的参数.原文:
Prior to calling
va_arg, ap must be initialized by a call to either va_start or va_copy, with no intervening call to va_end. Each invocation of the va_arg macro modifies ap to point to the next variable argument.如果
va_arg被调用时的参数有没有更多的ap,或与ap,如果T(促销)后的下一个参数的类型不兼容的行为是未定义的,除非:原文:
If
va_arg is called when there are no more arguments in ap, or if the type of the next argument in ap (after promotions) is not compatible with T, the behavior is undefined, unless:- 一种类型是一个带符号的整数类型,另一种类型是对应的无符号整数类型,和的值是表示在这两种类型;或原文:one type is a signed integer type, the other type is the corresponding unsigned integer type, and the value is representable in both types; or
- 一种类型是指针void和其他字符类型是一个指针.原文:one type is pointer to void and the other is a pointer to a character type.
目录 |
[编辑] 参数
| ap | - | va_list类型的一个实例
|
| T | - | 中的下一参数
ap的类型 原文: the type of the next parameter in ap |
[编辑] 扩展后的值
下一个变量参数
ap[编辑] 示例
#include <iostream> #include <cstdarg> #include <cmath> double stddev(int count, ...) { double sum = 0; double sum_sq = 0; va_list args; va_start(args, count); for (int i = 0; i < count; ++i) { double num = va_arg(args, double); sum += num; sum_sq += num*num; } return std::sqrt(sum_sq/count - (sum/count)*(sum/count)); } int main() { std::cout << stddev(4, 25.0, 27.3, 26.9, 25.7) << '\n'; }
输出:
0.920258
[编辑] 另请参阅
| 带可变参数函数的参数可以访问 原文: enables access to variadic function arguments (函数宏) | |
| (C++11) |
makes a copy of the variadic function arguments (函数宏) |
| 结束遍历可变参数函数的参数 原文: ends traversal of the variadic function arguments (函数宏) | |