Share via


_STATIC_ASSERT 宏觀

在編譯期間評估運算式,並在結果為 FALSE 時產生錯誤。

語法

_STATIC_ASSERT(
    booleanExpression
);

參數

booleanExpression
評估為非零 (TRUE) 或 0 (FALSE) 的運算式 (包括指標)。

備註

這個宏類似于 _ASSERT_ASSERTE ,不同之處在于 booleanExpression 是在編譯時期評估,而不是在執行時間評估。 如果 booleanExpression 評估為 FALSE (0),則會產生編譯器錯誤 C2466

範例

在此範例中,檢查 intsizeof 是否大於或等於 2 個位元組,以及 longsizeof 是否為 1 個位元組。 程式不會編譯,而且會產生 編譯器錯誤 C2466 ,因為 long 大於 1 個位元組。

// crt__static_assert.c

#include <crtdbg.h>
#include <stdio.h>

_STATIC_ASSERT(sizeof(int) >= 2);
_STATIC_ASSERT(sizeof(long) == 1);  // C2466

int main()
{
    printf("I am sure that sizeof(int) will be >= 2: %d\n",
        sizeof(int));
    printf("I am not so sure that sizeof(long) == 1: %d\n",
        sizeof(long));
}

需求

Macro 必要的標頭
_STATIC_ASSERT <crtdbg.h>

另請參閱

字母函數參考
_ASSERT、、 _ASSERTE_ASSERT_EXPR