C Programming: Memory, Pointers and the Stack ยท Functions and Scope
Locals are new on every call; a global is shared by everything; a static local keeps its value between calls.
#include <stdio.h>
int total_calls = 0; /* global: one copy for the whole program */
int next_ticket(void) {
static int ticket = 100; /* static local: keeps its value between calls */
int temp = 1; /* normal local: made fresh on every call */
ticket += temp;
total_calls++;
return ticket;
}
int main(void) {
int a = next_ticket();
int b = next_ticket();
printf("%d %d %d\n", a, b, total_calls);
return 0;
}total_calls changes from 0 to 1.ticket.next_ticket() has finished, so its variables are gone. The value it returned, 101, is stored in a.next_ticket(), with ticket = 101. It gets its own variables on the stack.temp is created on the stack with the value 1.total_calls changes from 1 to 2.ticket.next_ticket() has finished, so its variables are gone. The value it returned, 102, is stored in b.101 102 2.0.