C Basics: Check Fixed Buffer Relationships at Compile Time
A fixed packet buffer needs room for its header and payload. Express that relationship next to the constants so a later edit cannot silently break it.
Prepare a scratch directory
Tested on Linux amd64 with GCC 14.2.0. You need GCC with C17 support, Bash, a text editor, and the standard mktemp, rm, and rmdir utilities. No external library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as static-assertions-demo.c:
#include <stdio.h>
enum {
HEADER_CAPACITY = 12,
PAYLOAD_CAPACITY = 52,
PACKET_CAPACITY = 64
};
_Static_assert(HEADER_CAPACITY + PAYLOAD_CAPACITY == PACKET_CAPACITY,
"packet capacity must equal header plus payload");
_Static_assert(PAYLOAD_CAPACITY > 0, "payload must not be empty");
int main(void) {
unsigned char packet[PACKET_CAPACITY] = { 0 };
printf("Packet capacity: %zu\n", sizeof packet);
printf("Payload capacity: %d\n", PAYLOAD_CAPACITY);
return 0;
}Compile and run it. The program runs only if compilation succeeds:
gcc -std=c17 -Wall -Wextra -Werror -pedantic static-assertions-demo.c -o static-assertions-demo &&
./static-assertions-demoObserved output:
Packet capacity: 64
Payload capacity: 52Read the result
The assertions check integer constant expressions during compilation. They add no runtime branch and are not disabled by NDEBUG.
Apply it carefully
Static assertions cannot validate input received at runtime. Change PACKET_CAPACITY to 63 and compile again to see the compiler reject the relationship; diagnostic wording varies. Restore 64 before running. The equality checks sizes only, not packet encoding or bounds of later accesses.
See the WG14 C draft, section 6.7.10 for the underlying language rules.
Clean up
Remove only the source and executable created here, return to the starting directory, and remove the empty practice directory:
rm -- static-assertions-demo.c static-assertions-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.