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

Automatic duration variables

Automatic duration variables

What you'll learn: Understand how local variables are automatically created and destroyed within a function’s scope.

The disappearing act

Imagine a chalkboard in a busy classroom. When a specific teacher walks in to give a lecture, they grab a piece of chalk, write some temporary notes on the board, and use them for the next hour. However, as soon as the bell rings and the teacher leaves, a janitor immediately swipes the board clean for the next class.

In C, variables declared inside a function work exactly like those chalkboard notes. They are known as automatic duration variables (often just called "local variables"). They only exist while the function they belong to is actually running.

How it works in code

When you declare a variable inside a set of curly braces { }, C automatically allocates memory for it the moment that block of code starts. The moment the program hits the closing brace }, that memory is reclaimed, and the variable is "destroyed."

Take a look at this example:

#include <stdio.h>

void greet() {
    // 'visitor_count' is an automatic variable
    int visitor_count = 1; 
    visitor_count++;
    printf("Visitor number: %d\n", visitor_count);
} // <--- visitor_count is destroyed here!

int main() {
    greet(); // Prints 2
    greet(); // Prints 2 (not 3!)
    return 0;
}

In the code above, every time greet() is called, the variable visitor_count is born, assigned the value 1, incremented to 2, and then deleted from existence. When we call the function a second time, the computer doesn't remember what happened before; it starts the process fresh.

Why "Automatic"?

In the early days of C, programmers used the keyword auto to define these variables. While you can still write auto int x = 5;, nobody does because C assumes any variable declared inside a function is automatic by default.

This behavior is incredibly helpful. It prevents your computer's memory from getting cluttered with old data. You don't have to manually "clean up" your local variables; C handles the housekeeping for you, ensuring that once a function is done, its temporary data vanishes to make room for the rest of your program.

Key takeaway

Automatic variables are created when their block starts and are destroyed as soon as the block ends, meaning they do not "remember" their values between function calls.