Initialization with curly braces {}
What you'll learn: How to fill an array with values at the moment you create it using a simple list.
Setting the table
In previous lessons, you learned that an array is like a row of lockers. If you just declare an array like int scores[5];, it’s like having five empty lockers. To put something inside, you usually have to visit each locker one by one and place an item there.
However, C offers a shortcut. If you already know what data you want in your array, you can fill all the "lockers" at the exact moment you build them. We do this using a brace-enclosed list.
Using the curly braces {}
To initialize an array during declaration, you use the equals sign = followed by a comma-separated list of values wrapped in curly braces {}.
Think of it like a pre-packaged egg carton. Instead of buying an empty carton and then buying eggs separately to put in, you buy the carton already filled with eggs.
#include <stdio.h>
int main() {
// Initializing an array of 5 integers
int primeNumbers[5] = {2, 3, 5, 7, 11};
// Accessing the first element to verify
printf("The first prime is: %d\n", primeNumbers[0]);
return 0;
}
In this example, primeNumbers[0] becomes 2, primeNumbers[1] becomes 3, and so on. The compiler handles the heavy lifting of assigning each value to its corresponding index for you.
The "Automatic Sizing" trick
One of the coolest parts about using curly braces is that you don't even have to tell C how big the array is. If you leave the square brackets [] empty, C will count the items inside your curly braces and set the size automatically.
int levels[] = {1, 2, 3, 4, 5, 6}; // C automatically makes this an array of size 6
This is safer and more flexible. If you add a level to your list later, you don't have to remember to change the number inside the brackets. C simply sees six items and builds a "carton" with exactly six slots.
Key takeaway
Use curly braces {} to populate an array at the moment of creation, saving you from assigning values line-by-line.