C語言斷言的使用方法有以下幾種:
示例:
#include <assert.h>
#include <stdio.h>
int main() {
int x = 10;
assert(x > 0);
printf("x is positive\n");
return 0;
}
運行結果:
x is positive
示例:
#include <stdio.h>
_Static_assert(sizeof(int) == 4, "int size must be 4 bytes");
int main() {
printf("int size is 4 bytes\n");
return 0;
}
編譯錯誤:
error: static assertion failed: "int size must be 4 bytes"
示例:
#include <stdio.h>
#define my_assert(condition, message) \
if (!(condition)) { \
fprintf(stderr, "Assertion failed: %s\n", message); \
exit(1); \
}
int main() {
int x = 10;
my_assert(x > 0, "x must be positive");
printf("x is positive\n");
return 0;
}
運行結果:
x is positive
注意:斷言是用來檢查代碼邏輯錯誤的工具,一般在開發和調試階段使用。在發布生產環境的代碼時,應該禁用斷言或移除它們,以提高性能。