1. 程式人生 > 其它 >【C/C++】巨集引數多對一和巨集部分替換

【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;
}

執行結果: