Lesson 14 · 14 of 20
Scope and static variables · C
Understand where each variable lives in C: globals, locals, block variables and static ones, which keep their value between calls to a function.

A variable's scope is the part of the program where it exists. total_visits sits outside every function: it is global, and every function after it can read and change it. Use globals sparingly, since anything can modify them.
Variables declared inside a function are local: they are born on each call and vanish when it ends. That is why local is always 1: each time it starts again at 0 and gets one added.
With `static`, a local variable is created only once and keeps its value between calls, although it can still only be seen inside its function. calls counts 1, 2, 3, and next_ticket hands out consecutive numbers from 101. ++number adds one and gives back the new value straight away.
Every { } block has its own scope. The lives inside the block is a different variable that hides the outer one while the block lasts; once outside, the outer one is visible again, still 3. In the same way, the i from the for no longer exists after the loop.
Code · main.c
#include <stdio.h>int total_visits = 0; // global: every function below can use itvoid visit(const char page[]) { static int calls = 0; // static: keeps its value between calls int local = 0; // a normal local starts again on every call calls++; local++; total_visits++; printf("%-5s calls=%d local=%d\n", page, calls, local);}int next_ticket(void) { static int number = 100; // set to 100 only the first time return ++number; // add 1, then give the new value}int main(void) { visit("home"); visit("shop"); visit("cart"); printf("Total visits: %d\n", total_visits); for (int i = 0; i < 3; i++) printf("Ticket %d\n", next_ticket()); int lives = 3; { // a block has its own scope: this lives hides the outer one int lives = 99; printf("inside the block: lives = %d\n", lives); } printf("outside the block: lives = %d\n", lives); return 0;}Output · cc main.c -o main && ./main
home calls=1 local=1 shop calls=2 local=1 cart calls=3 local=1 Total visits: 3 Ticket 101 Ticket 102 Ticket 103 inside the block: lives = 99 outside the block: lives = 3
Key points
- A global variable is visible in the whole file.
- A local variable is born and dies with each call.
statickeeps the value between calls.- A
{ }block has its own scope. - An inner variable hides an outer one with the same name.
Exercise
Write a void log_message(const char text[]) function that numbers its messages with a static variable («1: start», «2: load»…) and call it four times.