c - 是否可以放的 ... 在 C 中的宏中?
问题描述
我正在尝试创建一个带有两个参数的函数,但它由一个宏重新映射以调用一个不同的隐藏函数,该函数接收的数据比传入的数据多。我将传递给隐藏函数的数据是类似的__LINE__
东西__FILE__
使用来自主函数的数据。
问题是可见函数需要能够传入任意数量的参数。下面的代码是该问题的简化示例。
#include <stdio.h>
#include <stdarg.h>
///////////////////////////////////////////////////////////
// This is what I would like to be able to do
#define average(count, ...) _average(__LINE__, count, ...)
///////////////////////////////////////////////////////////
// The average function
double _average(int _line, int count, ...) {
// Just a use for the extra variable
printf("Calculating the average of some numbers\n");
printf("on line %i\n", _line);
// The data contained within the "..."
va_list args;
va_start(args, count);
// Sum up all the data
double sum = 0;
for (int i = 0; i < count; i++) {
sum += va_arg(args, int);
}
// Return the average
return sum / count;
}
int main() {
printf("Hello, World!\n");
// Currently, this is what I have to do as the method I would prefer doesn't work...
printf("Average: %f\n", _average(__LINE__, 3, 5, 10, 15));
// Is there a way to use the above macro like the following?
// printf("Average 2: %f\n", average(3, 2, 4, 6));
return 0;
}
如果有帮助,此代码的输出如下:
Hello, World!
Calculating the average of some numbers
on line 160
Average: 10.000000
解决方案
要定义可变参数宏,...
请在参数列表中指定并使用__VA_ARGS__
:
#define average(count, ...) _average(__LINE__, count, __VA_ARGS__)
推荐阅读
- reactjs - 从 ReactNative 上的 API(jsonplaceholder) 删除数据
- pdf - 为什么此 PDF 中的纯青色图像未显示为纯青色?
- php - PHP - 我需要在一个循环中启动一个优化图像的类,以便在上传每个图像时对其进行优化?
- powershell - 为什么我的变量在 Powershell 中中断?(从文件中获取变量)
- computer-vision - 使用 opencv [计算机视觉] 从实时网络摄像头进行眼睛注视跟踪
- performance - 为什么在重新创建 neo4j DB 后 Cypher 查询性能会提高?
- arduino - Arduino 当按住按钮时,会显示一个连续的字母
- r - 连接循环和字符串输入以在 R 中形成列名
- node.js - 处理 SQS 事件的函数的预期响应是什么?
- json - 使用一个可解码结构使用 Swift 解析多个 JSON 文件