结合使用 assert 和 printf 的最佳实践

use*_*471 2 c

我目前正在使用以下语句来获取assertprintf协同工作,有没有更好的方法来做到这一点?

#define ASSERT(x) for(; !(x); assert(x))
#define ALLOC_CHECK(x, ...) ASSERT(x) printf(__VA_ARGS__ "\n");
ALLOC_CHECK(ptr != NULL, "Pointer not initialized");
Run Code Online (Sandbox Code Playgroud)

cma*_*ter 6

您不需要创建自己的assert()变体,您只需在断言中包含一条错误消息:

assert(someCondition && "Internal error: ... . Please report this bug.");
Run Code Online (Sandbox Code Playgroud)

由于assert()宏在失败时打印其参数,因此它还会打印您的字符串。