c / intermediate
Snippet
Compile-time Assertions with _Static_assert
_Static_assert (introduced in C11) allows checking conditions during the compilation phase rather than at runtime. If the condition is false, the compiler generates an error and stops, preventing the creation of an invalid binary.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>// Ensure the code is only compiled on systems with 4-byte integers_Static_assert(sizeof(int) == 4, "Error: int must be 32-bit for this protocol");struct DataPacket {char header[2];int payload;};_Static_assert(sizeof(struct DataPacket) == 8, "Warning: Unexpected padding in struct");int main() {printf("Architecture check passed.\n");return 0;}
Breakdown
1
_Static_assert(condition, "message");
Tests a constant expression; triggers a compiler error if the expression evaluates to zero.
2
sizeof(int) == 4
A constant expression evaluated by the compiler based on the target architecture.