C語言標準庫之

在 C 語言的標準庫 <assert.h> 中主要定義了一個宏函數 void assert (int expression); ,當函數的參數 expression 的值爲 0 時,assert() 函數將會把調用 assert(expression); 語句所在的文件名、行號和 expression 等信息一起輸出到標準輸出流中,並調用 C 的 abort() 系統調用方法中止程序的執行,讓程序員知道程序在這個地方出錯了。因此,assert() 函數是專門爲 debug 準備的:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int main()
{
    int a = 12, b = 24;
    assert(a > b);
    printf("a is larger than b!\n");

    return 0;
}

上述程序的輸出如下所示:

Assertion failed: a > b, file G:\CLibLearning\main.c, line 9

此處,printf 語句將不再執行,因爲運行到 assert 語句時程序就已經被中止退出。

當 debug 階段已經全部結束時,不需要逐一把源代碼中的調用 assert 的語句去掉,只需要#include <assert.h> 語句前添加宏 #define NDEBUG 即可以使得所有的 assert() 語句都失效:

#include <stdio.h>
#include <stdlib.h>

#define NDEBUG

#include <assert.h>


int main()
{
    int a = 12, b = 24;
    assert(a > b);
    printf("a is larger than b!\n");

    return 0;
}

上述程序將輸出:

a is larger than b!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章