是否可以将 的…放入C语言的宏中?

问题描述 投票:0回答:1

我正在尝试创建一个带有两个参数的函数,但是该宏将对其进行重新映射以调用一个不同的,隐藏的函数,该函数所接收的数据要多于传入的数据。我将要传递给该隐藏函数的数据就像__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

谢谢您的帮助!

c function macros arguments
1个回答
0
投票
要定义可变参数宏,请在参数列表中指定...并用__VA_ARGS__进行引用:
© www.soinside.com 2019 - 2024. All rights reserved.