當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C語言 assert用法及代碼示例

C語言assert頭文件(assert.h)中assert宏的用法及代碼示例。

用法:

void assert (int expression);
評估斷言
如果論點表達式函數形式的此宏的等於零(即表達式為),則會將一條消息寫入標準錯誤設備,然後abort被調用,終止程序執行。

顯示的消息的詳細信息取決於特定的庫實現,但至少應包括:expression其斷言失敗,源文件的名稱及其發生的行號。常用的表達式格式為:

Assertion failed: expression, file filename, line line number

如果在包含<assert.h>,名稱為的宏NDEBUG已經定義。這允許編碼器包含盡可能多的assert在調試程序時根據需要在源代碼中進行調用,然後通過簡單地添加如下行來將其全部禁用以用於生產版本:
/* assert example */
#include <stdio.h>      /* printf */
#include <assert.h>     /* assert */

void print_number(int* myInt) {
  assert (myInt!=NULL);
  printf ("%d\n",*myInt);
}

int main ()
{
  int a=10;
  int * b = NULL;
  int * c = NULL;

  b=&a;

  print_number (b);
  print_number (c);

  return 0;
}

在代碼的開頭,在包含之前<assert.h>

因此,此宏旨在捕獲編程錯誤,而不是用戶或運行時錯誤,因為通常在程序退出調試階段後將其禁用。

參數

expression
要評估的表達式。如果此表達式的計算結果為0,這會導致斷言失敗終止程序。

返回值



示例

/* assert example */
#include <stdio.h>      /* printf */
#include <assert.h>     /* assert */

void print_number(int* myInt) {
  assert (myInt!=NULL);
  printf ("%d\n",*myInt);
}

int main ()
{
  int a=10;
  int * b = NULL;
  int * c = NULL;

  b=&a;

  print_number (b);
  print_number (c);

  return 0;
}


在這個例子中assert用於中止程序執行,如果print_number以空指針作為屬性調用。在第二次調用該函數時會發生這種情況,這會觸發斷言失敗以發出錯誤消息。

注:本文由純淨天空篩選整理自C標準庫大神的英文原創作品 C assert function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。