_Static_assert C11 compile-time assertions

_Static_assert C11 compile-time assertions

_Static_assert checks an integer constant expression; zero fails with a message. Runtime values such as variables and function results are invalid in it.

CategoryC11 features
KindKeyword / Statement
C standardC11

📝 Syntax

_Static_assert(sizeof(int) >= 4, "int too small");

▶ Example

Edit the C code below and click Run; the server compiles and executes it:

Output:

int width assertion passed
ℹ️ Info The assertion uses sizeof(int) * CHAR_BIT >= 32, avoiding the assumption that a C byte is always 8 bits. It compiles for GCC 10.2's 32-bit int target and prints the success message. The expression checks total width, not value bits after excluding sign and padding bits.

📚 Related Tutorials

❓ FAQ

QDoes _Static_assert check its condition while the program runs?
ANo. It checks an integer constant expression during translation. If the condition is false, the translation unit fails to compile, so no corresponding runtime check exists in a generated program.
QWhy is CHAR_BIT needed when checking int's bit width?
Asizeof(int) is measured in C bytes, and CHAR_BIT gives the number of bits in one byte. Their product is the total bit width in that implementation; a byte cannot be assumed always to contain 8 bits.
QHow should I choose between _Static_assert and assert from assert.h?
AUse _Static_assert for compile-time facts such as type sizes and constant configuration, and assert for runtime conditions such as function inputs and program state. assert may also be affected by NDEBUG, whereas static assertions are not.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏