πŸ‡―πŸ‡΅ ζ—₯本θͺž | πŸ‡ΊπŸ‡Έ English

Global Variables

C global variables, scope, variable lifetime, and the static keyword explained.

πŸ“– What to learn on this page
βœ… Must-know essentials
  • Declared outside any function β†’ global
  • Visible and writable from every function
  • A local variable shadows a same-name global
⭐ Read if you have time
  • static hides from other files
  • extern references from other files
  • Avoid overusing globals

Scope β€” where a variable is visible

The region where a variable can be referenced β€” its scope β€” is determined by where you declare it.
int main(void) {
  int a = 10;          // valid inside main
  if (a > 0) {
    int b = 20;        // valid only inside this block
    printf("%d\n", a+b); // OK
  }
  // printf("%d\n", b);  ← error! b is out of scope
}
Local variable
Valid only inside the function or block. Destroyed on exit.
Global variable
Declared outside any function. Accessible from everywhere.
static variable
A local variable that keeps its value between calls.

Variable lifetime β€” when it's born and when it dies

Scope tells you where a variable is visible. Lifetime tells you when it's allocated in memory and when it gets freed.

Three kinds of lifetime

KindWhere declaredCreated whenDestroyed when
auto (local)inside a function/blockwhen the block is enteredwhen the block is exited
globaloutside any functionprogram startprogram end
staticinside a function (with static)program startprogram end
void example(void) {
  int        a = 1;   // auto: created per call, gone on exit
  static int b = 1;   // static: created once, value persists
  a++; b++;
  printf("a=%d b=%d\n", a, b);
}
int main(void) {
  example();  // a=2 b=2
  example();  // a=2 b=3  ← a resets, b persists
  example();  // a=2 b=4
}

Visualize the lifetime

Click the button to watch how each variable changes as example() is called three times.
Step 0 / 9
Call state
Variables in memory
Output

Global variables β€” shared across every function

#include<stdio.h>

int counter = 0;        // global variable (outside main, etc.)

void increment(void) {
  counter++;            // usable without any argument
}

int main(void) {
  increment();
  increment();
  increment();
  printf("%d\n", counter); // β†’ 3
}
Don't overuse them: globals are convenient, but it's hard to track down where they get modified, so they tend to invite bugs. Use them sparingly.

static variables β€” persist across calls

A regular local variable is destroyed as soon as the function returns, but adding static makes it live until the program ends.
void count(void) {
  static int n = 0;  // initialized to 0 only once
  n++;
  printf("Call count: %d\n", n);
}

int main(void) {
  count();  // β†’ 1
  count();  // β†’ 2
  count();  // β†’ 3
}
When to use it: when you want to count how many times a function has been called, or remember a previous result β€” especially when you need state without the risks of a full global.

Memory layout β€” where do variables actually live?

Local, global, and static variables are stored in different memory regions. That's the real reason their lifetimes differ.

Memory map of a C program

When a C program runs, memory is divided into five regions:
High address ↑
πŸ“š Stack
Local variables, function arguments, and return addresses.
Automatically allocated and freed with each function call.
↓ grows down ↓
(free space)
↑ grows up ↑
🧱 Heap
Dynamically allocated via malloc / free.
Managed explicitly by the programmer.
🌐 BSS (Uninitialized Data)
Uninitialized global and static variables.
Automatically zeroed at program start.
πŸ’Ύ Data (Initialized)
Initialized global and static variables.
Live for the entire program.
πŸ“œ Text (Code)
Machine code and string literals.
Read-only.
Low address ↓

Code mapped to regions

#include <stdio.h>
#include <stdlib.h>

int g_init = 100;        // πŸ’Ύ Data segment (initialized)
int g_uninit;            // 🌐 BSS (uninitialized β†’ auto-zeroed)

void func(void) {
    int local = 5;        // πŸ“š Stack (new copy per call)
    static int s = 0;    // πŸ’Ύ Data segment (created once)
    int *heap = malloc(sizeof(int)); // 🧱 Heap
    *heap = 42;
    free(heap);
}

int main(void) {
    func();
    return 0;
}

Variable types and their memory regions

Variable typeDeclared inMemory regionCreatedInitial value
Local (auto) Inside function πŸ“š Stack On function call Undefined (garbage)
Local (static) Inside function + static πŸ’Ύ Data / BSS At program start 0 or specified value
Global (initialized) Outside any function πŸ’Ύ Data At program start Specified value
Global (uninitialized) Outside any function 🌐 BSS At program start 0 (automatic)
malloc'd Dynamic inside function 🧱 Heap On malloc call Undefined (calloc: 0)
String literal Source code "..." πŸ“œ Text At program start Read-only

Function calls and the stack

Each function call pushes a stack frame. When the function returns, the frame is popped automatically.
void b(void) { int y = 20; }  // b's frame
void a(void) { int x = 10; b(); }  // a's frame
int main(void) { a(); return 0; }
Stack when main β†’ a() β†’ b() is in progress:
b() frame (y=20) ← top (pushed last)
a() frame (x=10)
main() frame
When b() returns, its frame is popped, then a() returns and its frame is popped too.
What is a stack overflow? Too much recursion or deeply nested calls can exhaust the stack region, triggering a segmentation fault.

Lifetimes, explained through memory regions

Short-lived = Stack
Local variables. Disappear the moment the function ends. Fast, but they can't persist across calls.
Long-lived = Data/BSS
Globals and statics. Live for the whole program. Always accessible, but overusing them hurts maintainability.
Flexible = Heap
Allocated with malloc and freed with free. You control both size and lifetime. Forget to free, and you get a memory leak.

Try it yourself β€” scope

scope.c
Output
Click Run...
πŸ’‘ Try these ideas too

Related lessons

Functions
Function Basics
Define and call C functions. Understand parameters and return values.
Basics
Variables
What are variables? How to use int, double, and char in C.
Functions
Prototypes & Macros
Prototypes and #define macros in C.
← Previous lesson
Lesson 28: Prototype & Macro
Next lesson →
Lesson 26: Arrays as Arguments

Review Quiz

Check your understanding of this lesson.

Q1. What is the initial value of an int global variable?

Undefined
0
-1

Global variables are automatically initialized to 0. Local variables hold an indeterminate value unless you initialize them yourself.

Q2. What is the key property of a static variable?

Its value is retained after the function returns
It is accessible from other files
It runs faster

A static local variable keeps its value between calls, so the next invocation sees the value from the previous one.

Q3. Why is heavy use of global variables discouraged?

Because they use too much memory
Because they can be modified from anywhere, causing bugs
Because they slow the program down

Globals can be changed from anywhere in the program, which leads to unintended modifications and hard-to-find bugs.

Share this article
Share on X Share on Facebook