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

Global variables and file scope

Global variables and file scope

What you'll learn: How to declare variables that live outside of functions and remain accessible throughout your entire program.

The "Town Square" vs. The "Private Home"

Imagine your C program is a small town. Up until now, we have been working with local variables. These are like items inside a private home (a function). Only the people inside that specific house know the item exists, and once everyone leaves the house, the item is tossed away.

Global variables, however, are like a statue in the Town Square. Because they are placed outside of any specific building, everyone in town can see them, use them, and even change them. More importantly, the statue doesn't disappear when a house closes; it stays there for as long as the town exists.

How to Declare Global Scope

In C, a variable has file scope (or global scope) when it is defined outside of any function, usually at the very top of your .c file. Because it isn't tucked away inside curly braces { }, every function beneath it can "see" it.

#include <stdio.h>

// This is a global variable
int global_gold_count = 100;

void visit_shop() {
    // This function can see and change the global variable
    global_gold_count -= 10;
    printf("Bought an item! Gold left: %d\n", global_gold_count);
}

int main() {
    printf("Starting gold: %d\n", global_gold_count);
    
    visit_shop();
    visit_shop();
    
    printf("Final gold balance: %d\n", global_gold_count);
    return 0;
}

Lifetime and Persistence

The "lifetime" of a global variable is the entire duration of your program. A local variable is born when a function starts and dies when the function ends. A global variable is born when the program starts and only dies when the program is shut down.

This makes them useful for tracking information that the whole program needs to share, like a player's score or a system setting. However, use them sparingly! If every function in your program can change the same variable, it can become very difficult to track down which function caused a bug.

Key takeaway

Global variables are declared outside functions, are accessible from anywhere in the file, and persist for the program's entire runtime.