【C/C++】宏参数多对一和宏部分替换

宏参数多对一:使用分号分隔多参数

宏部分替换:替换需要转换的再与后续宏接续

#include <stdio.h>

#define _MESS_FAILED()    printf("%s %d: ASSERT FAILED\r\n", __func__, __LINE__)
#define TU_BREAKPOINT()          \
do {                             \
    printf("TU_BREAKPOINT()\n"); \
} while (0)

#define TU_VERIFY_DEFINE(_cond, _handler, _ret) \
do {                                            \
    if (!(_cond)) {                             \
        _handler;                               \
        return _ret;                            \
    }                                           \
} while(0)

#define GET_3RD_ARG(arg1, arg2, arg3, ...)    arg3

// 宏参数多对一 ';'
#define ASSERT_1ARGS(_cond)          TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); TU_BREAKPOINT(), false)
#define ASSERT_2ARGS(_cond, _ret)    TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); TU_BREAKPOINT(), _ret)

// 宏部分替换
#define TU_ASSERT(...)    GET_3RD_ARG(__VA_ARGS__, ASSERT_2ARGS, ASSERT_1ARGS, UNUSED)(__VA_ARGS__)

typedef enum{false, true}    bool;

bool assert_function_true(void)
{
    TU_ASSERT(true);
}

bool assert_function_false(void)
{
    TU_ASSERT(false);
}

int main()
{
    /*  Write C code in this online editor and run it. */
    printf("Hello, World! \n");
    TU_ASSERT(1);
    printf("-------------------------\n");
    printf("%d\n", assert_function_true());
    printf("-------------------------\n");
    printf("%d\n", assert_function_false());
    printf("-------------------------\n");
    TU_ASSERT(0);

    return 0;
}

执行结果:

posted @ 2022-03-29 09:22  壹点灵异  阅读(346)  评论(0编辑  收藏  举报