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

Global Variables

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

Scope β€” Where a Variable Is Visible

The region where a variable can be referenced (its scope) is determined by where it is declared.
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 everywhere.
static variable
A local variable that retains its value between calls.

Variable Lifetime β€” When It Is Born and When It Dies

Scope tells you "from where it is visible." Lifetime tells you when the variable is allocated and freed in memory.

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 animate how each variable changes as example() is called three times.
Step 0 / 9
Call state
Variables in memory
Output

Global Variables β€” Shared Across All Functions

#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: Globals are convenient, but it is hard to trace where they are modified, so they invite bugs. Keep them to a minimum.

static Variables β€” Persist Across Calls

A regular local variable is destroyed when 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: When you need to know "how many times a function was called" or remember a previous result β€” especially when you want state without the risks of globals.

Memory Layout β€” Where Do Variables Actually Live?

Local, global, and static variables are stored in different memory regions. This is the real reason their "lifetimes" differ.

Memory map of a C program

When a C program runs, memory is divided into 5 regions:
High address ↑
πŸ“š Stack
Local variables, function arguments, return addresses.
Automatically allocated/freed on 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.
Auto-zeroed at program start.
πŸ’Ύ Data (Initialized)
Initialized global and static variables.
Lives 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. Returning automatically pops it.
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 too many nested calls exhausts the stack region, causing a Segmentation Fault.

"Lifetime" explained via memory regions

Short-lived = Stack
Local variables. Disappear when function ends. Fast, but can't persist across calls.
Long-lived = Data/BSS
Global/static. Live for the whole program. Always accessible, but overuse hurts maintainability.
Flexible = Heap
Allocated with malloc, freed with free. You control size and lifetime. Forgetting free = memory leak.

Try It Yourself β€” Scope

scope.c
Output
Click Run...
Advertisement

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
Prototypes & Macros
Next lesson β†’
Arrays as Arguments

Quick 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 have an indeterminate value unless initialized.

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; the next invocation sees the previous value.

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 anywhere in the program, which leads to unintended modifications and hard-to-find bugs.

Share this article
Share on X Share on Facebook