【问题标题】:Is it possible to put <stdarg.h>'s ... in a macro in C?是否可以将 <stdarg.h> 的 ... 放在 C 中的宏中?
【发布时间】:2020-06-27 22:42:50
【问题描述】:

我正在尝试创建一个带有两个参数的函数,但它被一个宏重新映射以调用一个不同的隐藏函数,该函数接收的数据比传入的数据多。我将传递给隐藏函数的数据是东西比如__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】:

    要定义可变参数宏,请在参数列表中指定...,并使用__VA_ARGS__ 引用它们:

    #define average(count, ...) _average(__LINE__, count, __VA_ARGS__)
    

    【讨论】:

    • 请注意,如果您在计数后需要一个空列表,生活会变得更加棘手 - 这是可行的,但解决方案并不完全令人满意(使用 GCC 扩展的不可移植性,或者丢失检查,或者...... )。但是,如果在计数之后总是至少有一个参数,那么这很好。您可以在#define macro for debug printing in C? 找到有关该问题的讨论
    猜你喜欢
    • 2012-08-01
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 2020-01-11
    相关资源
    最近更新 更多