C 中的宏和上下文输出

macros and contextual output in C

我试图理解文件中宏的以下描述:

/*
 * The following macros provide wrapper calls to the test functions with
 * a default description that indicates the file and line number of the error.
 *
 * The following macros guarantee to evaluate each argument exactly once.
 * This allows constructs such as: if (!TEST_ptr(ptr = MYFOO_malloc(..)))
 * to produce better contextual output than:
 *      ptr = MYFOO_malloc(..);
 *      if (!TEST_ptr(ptr))
 */

我无法理解上述描述中宏在这种情况下有何帮助?

使用宏可以让您使用 Standard Predefined Macros,例如 __LINE____FILE__,如

所示

a default description that indicates the file and line number of the error.

以静默方式将调试信息添加到您的函数调用中。

这是一个使用 GCC Statement Expressions 的示例,以确保仅对用作宏参数的表达式求值一次:

#include <stdio.h>
#include <stdlib.h>

#define debug_test_ptr(ptr) ({ \
        void *p = (ptr); \
        fprintf(stderr, "testing %p in %s at line %d.\n", \
                p, __FILE__, __LINE__); \
        p; })

#define debug_malloc(sz) ({ \
        size_t s = (sz); \
        fprintf(stderr, "malloc(%zu) called in %s at line %d.\n", \
                s, __FILE__, __LINE__); \
        malloc(s); })

int main(void) {
    char *foo;

    if (!debug_test_ptr(foo = debug_malloc(100)))
        fprintf(stderr, "malloc failed!\n");

    free(foo);
}

输出:

malloc(100) called in info.c at line 19.
testing 0x117a2a0 in info.c at line 19.