← C roadmap

Topic 4 of 15 · Beginner

Functions & Recursion

Declarations, call by value, scope, static and recursion.

Concept

A function has a prototype (declaration), a definition and calls. C passes arguments by value — the function gets copies.

To let a function change a caller's variable, pass its address (a pointer).

A static local variable keeps its value between calls. Recursion needs a base case to stop.

Code (C17)

#include <stdio.h>

void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }

int counter(void) { static int n = 0; return ++n; }

long fib(int n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }

int main(void) {
    int x = 1, y = 2;
    swap(&x, &y);
    printf("%d %d\n", x, y);         // 2 1
    counter(); printf("%d\n", counter()); // 2
    printf("%ld\n", fib(10));        // 55
    return 0;
}

Remember

  • C is always call by value.
  • Pointers simulate call by reference.
  • static locals persist between calls.

Interview questions

Call by value vs call by reference?

By value copies the argument; by reference (via pointer in C) lets the function modify the original.

Storage classes in C?

auto, register, static and extern — they control lifetime, scope and linkage.

Practise C with the AI mentor

Lesson test

Take an 8-question test on “Functions & Recursion” — concepts, output prediction, bug spotting and interview questions.

Can't find a C topic you need for exams or placements? Request it and we'll add it.