Initialization of local vs global arrays
What you'll learn: How to predict the starting values of your array elements based on where they are declared in your code.
The Clean Slate vs. The Leftovers
In C, the "location" of your array—where you define it—determines its starting state. Imagine two different scenarios: a professionally cleaned hotel room and a messy shared kitchen.
When you declare an array outside of any function (a global array), C acts like a diligent hotel maid. It ensures every single "room" (index) in that array is wiped clean and set to zero before the program even starts.
However, when you declare an array inside a function (a local array), C prioritizes speed over cleanliness. It grabs a chunk of memory that was recently used by another part of your computer and hands it to you immediately. C doesn't bother clearing it out, meaning your array might contain "garbage values"—random numbers left over from whatever happened in that memory space seconds ago.
Seeing the Difference in Code
Notice how the global array is defined at the very top, while the local array lives inside main().
#include <stdio.h>
// Global array: Automatically initialized to all zeros
int globalArray[3];
int main() {
// Local array: Contains random "garbage" values
int localArray[3];
printf("Global [0]: %d\n", globalArray[0]); // Will print 0
printf("Local [0]: %d\n", localArray[0]); // Will print something unpredictable (e.g., 32764)
return 0;
}
Why This Matters
Relying on a local array to be empty is a classic beginner mistake that leads to "heisenbugs"—bugs that appear and disappear randomly. If your local array represents a score tracker, starting with a garbage value like 14829 instead of 0 will break your logic instantly.
To fix this, you can manually force a local array to behave like a global one by using {0} during declaration:
int localArray[3] = {0};
This tells C, "I know you're in a hurry, but please clear this specific space for me."
Key takeaway
Global arrays are automatically initialized to zero, while local arrays contain unpredictable garbage values unless you manually initialize them.