Course contentsShow
← C
Lesson 77 of 1,2192. Variables and TypesFree lesson

Garbage values and uninitialized variables

Garbage values and uninitialized variables

What you'll learn: Why your programs might produce unpredictable results if you forget to give your variables a starting value.

The "Dirty Drawer" Analogy

Imagine you have a chest of drawers in your house. When you buy a new chest from the store, you expect the drawers to be empty. However, computer memory (RAM) doesn't work that way.

In C, declaring a variable is like claiming a specific drawer for your data. But here is the catch: C doesn't "clean" the drawer for you when you claim it. Whatever was left in that memory location by a previous program—an old piece of a web browser, a fragment of a document, or a random number—stays there. This leftover data is known as a garbage value.

The Risk of Uninitialized Variables

When you declare a variable but do not assign it a value, it is called an uninitialized variable. If you try to use this variable in a calculation or print it to the screen, C will simply read whatever "garbage" happens to be sitting in that memory slot at that exact microsecond.

Look at this example:

#include <stdio.h>

int main() {
    int score; // Declared, but not initialized
    
    // This is dangerous! We are adding 10 to "garbage"
    score = score + 10; 
    
    printf("The score is: %d", score);
    
    return 0;
}

If you run this code, you might expect the score to be 10. Instead, you might see a result like -14283741. This happens because score started as a random mess, and adding 10 to a random mess just results in a slightly different random mess.

Why doesn't C fix this?

C is designed for speed and efficiency. Automatically zeroing out every piece of memory you ask for takes a tiny amount of time. C assumes that you, the programmer, want total control. It expects you to "clean the drawer" yourself by assigning a value immediately.

To avoid bugs that are incredibly hard to track down, get into the habit of initializing your variables as soon as you create them: int score = 0;. This ensures your program starts from a clean slate every time.

Key takeaway

Always initialize your variables upon declaration to prevent unpredictable "garbage values" from breaking your logic.