例子代码:
#include <stdio.h> #include <assert.h> int test_assert(int x) { assert(x <= 4); return x; } int main() { int i; for (i=0; i<=9; i++) { test_assert(i); printf("i = %d\n", i); } return 0; }linux环境:
1:带debug的编译和执行
totoro@totoro-Lenovo-IdeaPad-Y470:~/program$ gcc assert_test.c
totoro@totoro-Lenovo-IdeaPad-Y470:~/program$ ls
a.out assert_test.c
totoro@totoro-Lenovo-IdeaPad-Y470:~/program$ ./a.out
i = 0
i = 1
i = 2
i = 3
i = 4
a.out: assert_test.c:6: test_assert: Assertion `x <= 4' failed.
已放弃 (核心已转储)
2:release版本的编译和执行
totoro@totoro-Lenovo-IdeaPad-Y470:~/program$ gcc -DNDEBUG assert_test.c
totoro@totoro-Lenovo-IdeaPad-Y470:~/program$ ./a.out
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
totoro@totoro-Lenovo-IdeaPad-Y470:~/program$
windows下一般只需在编译时指定debug还是release版本就可以了。
参考资料wiki地址:
https://en.wikipedia.org/wiki/Assert.h