- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - static_assert() 宏
C 的 assert 庫 static_assert() 宏是 C11 標準中引入的一個強大工具,允許您執行編譯時斷言。這意味著您可以編譯時檢查某些條件,而不是執行時,從而儘早發現開發過程中的潛在錯誤。
語法
以下是 static_assert() 宏的 C 庫語法:
static_assert (boolean_expression, message);
引數
此宏接受以下引數:
boolean_expression − 這是一個編譯器在編譯時計算的常量表達式。如果此表示式計算結果為 0(false),則編譯失敗。
message − 這是一個字串字面量,在斷言失敗時提供錯誤描述。如果斷言失敗,則在編譯期間顯示此訊息。
返回值
此宏不返回值。相反,如果斷言為真,則允許編譯繼續;如果斷言為假,則導致編譯時錯誤。
示例 1:確保資料型別的尺寸
此示例檢查 int 的大小是否為 4 位元組。如果不是,則編譯失敗並顯示訊息“int 必須為 4 位元組”。
#include <assert.h>
static_assert(sizeof(int) == 4, "int must be 4 bytes");
int main() {
return 0;
}
輸出
上述程式碼產生以下結果:
error: static assertion failed: "int must be 4 bytes"
示例 2:檢查結構對齊
在此示例中,我們使用 offsetof 宏來確保 MyStruct 的 int b 成員與 4 位元組邊界對齊。如果不是,則編譯失敗。
#include <assert.h>
struct MyStruct {
char a;
int b;
};
static_assert(offsetof(struct MyStruct, b) % 4 == 0, "int b must be aligned to 4 bytes");
int main() {
return 0;
}
輸出
執行上述程式碼後,我們得到以下結果:
error: static assertion failed: "int b must be aligned to 4 bytes"
廣告