C Programming: Memory, Pointers and the Stack ยท Functions and Scope

Scope: Local, Global and static

Locals are new on every call; a global is shared by everything; a static local keeps its value between calls.

scope_static.c

#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;
}

Step by step

  1. First call to next_ticket.
  2. temp is a normal local: created fresh, set to 1.
  3. ticket: 100 + 1 = 101.
  4. total_calls changes from 0 to 1.
  5. The method returns ticket.
  6. next_ticket() has finished, so its variables are gone. The value it returned, 101, is stored in a.
  7. C calls next_ticket(), with ticket = 101. It gets its own variables on the stack.
  8. temp is created on the stack with the value 1.
  9. Second call: ticket remembered 101.
  10. total_calls changes from 1 to 2.
  11. The method returns ticket.
  12. next_ticket() has finished, so its variables are gone. The value it returned, 102, is stored in b.
  13. It prints 101 102 2.
  14. The method returns 0.
  15. 101 102 2: the static ticket and the global counter both survived between calls.