Omitting size during initialization
What you'll learn: How to let the C compiler automatically calculate the size of an array based on the number of elements you provide.
Letting the compiler do the math
When you declare an array in C, you usually put a number inside the square brackets, like int scores[5]. This tells the computer exactly how much memory to set aside. However, if you are providing the data right away using curly braces, you can leave those brackets empty.
Think of it like ordering a pizza. Usually, you have to tell the shop exactly how many slices you want. But if you walk into the shop and point at a pre-made tray of garlic knots, the baker doesn't need you to tell them there are six knots; they can see the six knots sitting right there on the tray.
In C, if you write int numbers[] = {10, 20, 30};, the compiler looks at your list, counts three items, and automatically treats it as int numbers[3].
Why use this?
This technique is a favorite among programmers because it prevents "off-by-one" errors and makes your code easier to maintain.
Imagine you have a list of high scores. If you manually set the size to [4] but then add a fifth score to the list later, the compiler will get confused or throw an error. By leaving the brackets empty, you can add or remove items from your list as much as you want during development, and the compiler will adjust the array's size every time you hit "build."
Seeing it in action
Here is how you initialize an array without explicitly defining the size:
#include <stdio.h>
int main() {
// The compiler counts 4 elements and sets the size automatically
int luckyNumbers[] = {7, 13, 21, 42};
// Even though we didn't write [4], the array has 4 slots
printf("The first number is: %d\n", luckyNumbers[0]);
printf("The last number is: %d\n", luckyNumbers[3]);
return 0;
}
One important rule to remember: you can only omit the size if you are providing the data at the exact same moment you create the array. You cannot leave the brackets empty if you plan to fill the array with data later on, because the compiler needs to know how much memory to reserve upfront.
Key takeaway
If you initialize an array with a list of values, you can leave the brackets [] empty and let the compiler count the elements for you.