Skip to content
Codescope

Functions & scope

Parameters are copies; locals, globals and static all live differently.

intro9 min7 steps

Before you start

A **function** is a named block of code you can run whenever you need it. Instead of writing the same 10 lines in five different places, you write them once as a function and call it five times.

**Scope** is the rule that decides which names you can see from where. A variable declared inside a function only exists inside that function — nobody else can touch it, and it disappears the moment the function returns.

This lesson watches a function get called, receive a copy of its arguments, do work in its own private space, and return. You will also see the three lifetimes variables can have: local (dies with the function), static (survives between calls), and global (lives forever).

Stack

each function gets its own frame
main()
val
42

Static storage

lives for the entire program
Static / global
global
100
visible everywhere

global lives in static storage. val lives in main's frame.

Step 1 of 7. main has its own frame. When `main` starts, the global variable `global` already exists — it was initialised before main was called. Locals like `val` are created inside the frame. A global variable is visible to every function. A local is visible only inside the one that declared it.

01 / 07

Step 01 / 07

main has its own frame

When main starts, the global variable global already exists — it was initialised before main was called. Locals like val are created inside the frame.

A global variable is visible to every function. A local is visible only inside the one that declared it.

functions-and-scope.cC
#include <stdio.h>int global = 100;void increment(int x) {   // x is a copy    x = x + 1;    printf("inside: %d\n", x);  // 43}int add(int a, int b) {    int sum = a + b;    return sum;                  // copy out}int counter(void) {    static int n = 0;    n++;    return n;}int main(void) {    int val = 42;    increment(val);    printf("outside: %d\n", val);  // still 42    int result = add(10, 20);    printf("%d\n", counter());  // 1    printf("%d\n", counter());  // 2}