assert ()- 驗證條件
格式
#include <assert.h>
void assert(int expression);語言層次
ANSI
安全執行緒
否
說明
如果 表示式 為 false (零) ,則
assert() 函數會將診斷訊息列印至 stderr ,並中斷程式。 診斷訊息具有下列其中一種格式,視編譯期間使用的語言層次而定:Assertion failed: expression, file filename, line line-number.Assertion failed: expression, file filename, line line-number, function function-name.如果 表示式 為 true (非零) ,則 assert() 函數不會採取任何動作。
使用 assert() 函數來識別程式邏輯錯誤。 請選擇 表示式 ,只有在程式如您想要的般運作時,才會保留 true。 在除錯程式之後,您可以使用特殊無除錯 ID NDEBUG ,從程式中移除 assert() 呼叫。 如果您使用 #define 指引將 NDEBUG 定義為任何值,則 C 前置處理器會將所有主張呼叫展開至 void 表示式。 如果您使用 NDEBUG ,則必須先定義它,然後再將 <assert.h> 併入程式中。
回覆值
此方法不會傳回任何值。
附註:
assert() 函數定義為巨集。 請勿將 #undef 指引與 assert()搭配使用。範例
在此範例中,
assert() 函數會測試 string 是否為空字串及空字串,並在處理這些引數之前驗證 length 是否為正數。#include <stdio.h>
#include <assert.h>
void analyze (char *, int);
int main(void)
{
char *string = "ABC";
int length = 3;
analyze(string, length);
printf("The string %s is not null or empty, "
"and has length %d \n", string, length);
}
void analyze(char *string, int length)
{
assert(string != NULL); /* cannot be NULL */
assert(*string != '\0'); /* cannot be empty */
assert(length > 0); /* must be positive */
}
/**************** Output should be similar to ******************
The string ABC is not null or empty, and has length 3
*****************************************************************/