Designated initializers (C99)
What you'll learn: How to initialize specific elements in an array by their index rather than their position in a list.
The "Skipping" Problem
In traditional C, if you wanted to initialize a large array where only the very last element had a value, you were forced to provide values for everything leading up to it. For example, to set the 100th element to 5, you would have to write out ninety-nine zeros first. This is tedious, error-prone, and makes your code hard to read.
Picking Your Slots
Introduced in the C99 standard, designated initializers allow you to "point" directly to the index you want to fill. Think of it like a parking lot. Instead of filling the spots in order starting from the entrance (Slot 0, Slot 1, Slot 2...), you can simply say, "Put the red car in Slot 50."
You do this using the square bracket syntax [index] = value inside the curly braces.
How it looks in code
You can initialize specific indices in any order. Any index you don't mention is automatically set to zero.
#include <stdio.h>
int main() {
// We create an array of 10 integers.
// We only care about the first, fifth, and last elements.
int scores[10] = {
[0] = 100, // The first element
[4] = 50, // The fifth element
[9] = 75 // The tenth (last) element
};
// Everything else (like scores[1], scores[2], etc.) is now 0.
printf("Score at index 4 is: %d\n", scores[4]);
printf("Score at index 1 is: %d\n", scores[1]);
return 0;
}
Flexibility and Range
Designated initializers are particularly powerful when dealing with large arrays or lookup tables. If you define an array without a fixed size—like int arr[] = {[10] = 1};—the compiler is smart enough to see the highest index mentioned (10) and automatically make the array large enough to hold it (size 11).
This feature makes your code "self-documenting." When someone reads your code, they immediately see exactly which positions are important, rather than squinting at a long list of zeros trying to count the commas.
Key takeaway
Designated initializers let you use [index] = value to fill specific array slots, automatically setting all unmentioned elements to zero.