assert.h 可多次包含,效果取決於包含時是否定義 NDEBUG:
NDEBUG:assert(expr) 為活性斷言,expr==0 時打印診斷信息並 abort()。NDEBUG:assert(expr) 展開為空操作(甚至不求值 expr)。__FILE__)__LINE__)__func__,C99)輸出目標:控制台程序 → stderr;GUI 程序 → MessageBox。
[cpp]
#include
#include
int main() {
FILE *fd = fopen("/home/user/file.txt", "r");
assert(fd); // 若 fd==NULL 觸發斷言
fclose(fd);
return 0;
}
[cpp]
// 無 NDEBUG
#include
#include
int main() {
printf("1 ok hello\n");
assert(1==4);
printf("2 ok exit\n"); // 不會執行
}
// 輸出:1 ok hello → Assertion `1==4' failed → Abort
// 定義 NDEBUG
#define NDEBUG
#include
#include
int main() {
printf("1 ok hello\n");
assert(1==4); // 被移除
printf("2 ok exit\n"); // 正常執行
}
// 輸出:1 ok hello → 2 ok exit
[cpp]
#define assert(test) if(!(test)) \
fprintf(stderr, "Assertion failed: %s, file %s, line %d\n", #test, __FILE__, __LINE__), abort()
assert(x++ > 0) 在 Release 下 x++ 不執行,導致邏輯差異。斷言表達式必須無副作用。if 判斷返回錯誤碼)。-DNDEBUG (GCC/Clang) 或 /DNDEBUG (MSVC) 可批量禁用斷言。