C static assertions use _Static_assert(condition, "message") (C11) to verify compile-time constraints. If the condition is false, compilation fails with the message. Use for checking sizeof, alignment, configuration invariants.
Use static assertions to catch configuration errors at compile time instead of runtime.
// compile: gcc -std=c11 -o static_assert static_assert.c // run: ./static_assert // description: compile-time assertions #include <stdio.h> #include <limits.h> #include <stdint.h> // Check that int is at least 32 bits _Static_assert(sizeof(int) >= 4, "int must be at least 32 bits"); // Check that pointers fit in uint64_t _Static_assert(sizeof(void *) <= sizeof(uint64_t), "pointer too large for uint64_t"); // Check enum values enum Color { RED = 0, GREEN = 1, BLUE = 2 }; _Static_assert(RED == 0, "RED must be 0"); // Configuration-dependent assertion #define MAX_CONNECTIONS 1024 _Static_assert(MAX_CONNECTIONS > 0, "MAX_CONNECTIONS must be positive"); // Struct alignment check struct aligned_data { int x; double d; }; _Static_assert(sizeof(struct aligned_data) <= 32, "aligned_data struct too large"); int main() { printf("All static assertions passed\n"); printf("sizeof(int) = %zu\n", sizeof(int)); printf("sizeof(void*) = %zu\n", sizeof(void *)); return 0; }
Basic syntax:
_Static_assert(condition, "message") at file or function scopeCommon checks:
sizeof(type) == expected_sizeBenefits:
C11 vs earlier:
_Static_assert()#error pragma for conditional compilationMacros for cleaner syntax:
#define STATIC_ASSERT(expr, msg) _Static_assert((expr), msg) #define ASSERT_SIZE(type, size) \ STATIC_ASSERT(sizeof(type) == size, #type " has wrong size")
Limitations: