c / expert
Snippet
Designated Initializers for Sparse Arrays
Designated initializers allow you to initialize specific array indices or struct members by name/index. For arrays, this is particularly useful for mapping non-sequential constants (like error codes) to strings, leaving uninitialized elements as zero/NULL.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>const char* get_error(int code) {static const char* const errors[] = {[0] = "Success",[404] = "Not Found",[500] = "Internal Server Error"};return (code >= 0 && code < 501) ? errors[code] : "Unknown";}
Breakdown
1
[404] = "Not Found"
Explicitly sets the value at index 404, regardless of prior elements.