1、assert的作用
int i = 0;
assert(i == 0);
printf("hello_world\n");
當括號中的表達式爲true時,程序繼續執行下一條語句。
當括號中的表達式爲false,程序將直接終止運行,並輸出相應信息,如終止所在行等。
2、取消assert的功能
assert函數一般用在代碼調試,在程序真正運行時並不希望總是出現程序異常終止的現象。
#define NDEBUG
#include <assert.h>
這兩條語句結合使用即可取消assert的終止,而不需要註釋掉代碼。
3、恢復assert的功能
#undef NDEBUG
#include <assert.h>
在使用2中的代碼取消assert的作用後,可以使用上面的代碼恢復其功能。
這兩條語句只對其後面的assert有效果,對前面的無效。
4、示例代碼片
#define NDEBUG
#include
#include
void func1()
{
int i = 0;
assert(i == 0);
printf("%d\n",i);
i++;
assert(i == 0);//define NDEBUG cannot abort
printf("%d\n",i);
}
#undef NDEBUG
#include
void func2()
{
int i = 0;
assert(i == 0);
printf("%d\n",i);
i++;
assert(i == 0);//undef NDEBUG should abort
printf("%d\n",i);
}
int main(int argc,char *argv[])
{
if(argc < 2)
return 0;
if(argv[1][0] == '1')
func1();
else if(argv[1][0] == '2')
func2();
return 0;
}