c-static-assertions
Table of Contents
C static assertions
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.
Example
// 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; }
Common patterns
Basic syntax:
_Static_assert(condition, "message")at file or function scope- Condition evaluated at compile time
- Message printed if assertion fails
Common checks:
sizeof(type) == expected_size- Platform word size assumptions
- Configuration invariants
- Enum value checks
Benefits:
- Fails at compile time, not runtime
- Catches platform/config issues early
- Documents assumptions
- Zero runtime overhead
C11 vs earlier:
- C11:
_Static_assert() - C99 and earlier: no standard static assertions
- GCC:
#errorpragma for conditional compilation
Macros 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:
- Condition must be compile-time constant
- Can't use runtime values
- Only works for static checks
c-static-assertions.md · Last modified: by 127.0.0.1
