Skip to content

Instantly share code, notes, and snippets.

@RaphGL
Last active November 13, 2023 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RaphGL/acda966585a00b04782249038260aacc to your computer and use it in GitHub Desktop.
Save RaphGL/acda966585a00b04782249038260aacc to your computer and use it in GitHub Desktop.
Static array indices in Modern C

Static Indices

C99 adds static indices letting you preserve size information for array parameters. This means that there's a guarantee that an array will never be null and has to have at least the specified number of items instead of just decaying into pointer.

So say we have this function signature:

void print_msg(char msg[10]);

You could call it this way:

print_msgs(NULL);
print_msgs("Hi");

In both cases if you don't handle NULL and don't consider the sentinel termination (\0 for c strings) you'll end up dereferencing NULL or going out of bounds for the array causing undefined behavior with static you can have a guarantee that the array will always be at least 10 elements

void print_msg(char msg[static 10]);

so you'll get help from the compiler with checking that you're doing the right thing

This also means that you can make an array non null by just making it be at least size 1

void print_msg(char msg[static 1], size_t s);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment