Skip to content
LumenaryAcademy
Foundations 55 min

Control flow and functions

Decisions, loops and switch statements in C, and functions with prototypes, pass-by-value, recursion, scope and static storage.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

The shape of a C program

You already know how to make decisions and repeat work; the Start level of Lumenary CS did it in Python. C has the same ideas with a different spelling: conditions in parentheses, blocks in braces, and a semicolon after every statement. What is new in C is the role of functions. A C program is a collection of functions, each with a declared type for every parameter and for the result, and the compiler checks every call against those declarations. There are no classes and no modules in the language itself: functions, and the files they live in, are the units of design.

This lesson covers control flow quickly, spending time on the parts that differ from other languages (switch and its fall-through, do-while, goto for cleanup), and then functions in depth: prototypes, pass-by-value, recursion, and the static keyword, which means two different things depending on where you write it.

DefinitionsH

Control flow in C

if and else

c
if (temperature > 30) {
    puts("hot");
} else if (temperature > 15) {
    puts("mild");
} else {
    puts("cold");
}

The condition is any scalar expression; zero means false. Braces are optional around a single statement, but leaving them out is a well-known source of bugs (the 2014 "goto fail" vulnerability in Apple's TLS code was a duplicated line under a brace-less if), so most style guides require them.

Loops

LoopUse it when
while (cond) { … }you test before each pass and may run zero times
do { … } while (cond);the body must run at least once
for (init; cond; step) { … }you have a counter or iterator with a start, a test and a step

break leaves the innermost loop or switch at once; continue skips to the next iteration (in a for loop, to the step). Since C99 you can declare the counter inside the for (for (int i = 0; …)), which limits its scope to the loop.

A few loop idioms recur in every C code base. for (size_t i = 0; i < n; i++) walks the n elements of an array, with an unsigned index that matches the type of sizes. for (;;) (or while (1)) is an intentional infinite loop, left with break or return from inside, typical of event loops and parsers. And a sentinel loop runs until it meets a special value, such as the zero byte at the end of a string, which you will write many times in lesson 5.

switch

switch compares an integer expression against constant case labels and jumps to the matching one. Only integers (including characters and enumeration constants) can be switched on; to choose between strings you compare them one by one with strcmp in an if/else chain, or look them up in a table. Compilers often turn a dense switch into a jump table, a single indexed jump, which is why it can be faster than a long if chain. Execution then continues downward until a break, falling through into the following cases. That is useful when several cases share code and dangerous when you forget a break; GCC's -Wextra includes -Wimplicit-fallthrough, which warns about a case that runs into the next without a comment or (in C23) a [[fallthrough]]; attribute saying it is intended.

Definition— function prototype

A function prototype declares a function's name, return type and parameter types, such as int days_in_month(int month, int year);, without its body. The compiler uses it to check calls and to convert arguments to the parameter types. A function must be declared before it is called; a definition earlier in the file also serves as a declaration.

ComputationC

Functions at work

A calendar with switch

The program below uses a function that returns a bool and another built on a switch. It also uses a small array, int years[]; arrays are the next lesson's subject, and for now years[i] simply means element number i.

c
#include <stdbool.h>
#include <stdio.h>

/* Gregorian rule: every 4th year, except centuries, except every 400th year. */
bool is_leap_year(int year) {
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}

int days_in_month(int month, int year) {
    switch (month) {
    case 2:
        return is_leap_year(year) ? 29 : 28;
    case 4:
    case 6:
    case 9:
    case 11:
        return 30;              /* several cases can share one body */
    default:
        return 31;
    }
}

int main(void) {
    int years[] = {1900, 2000, 2024, 2026};
    for (int i = 0; i < 4; i++) {
        int y = years[i];
        printf("%d: leap %s, February has %d days\n",
               y, is_leap_year(y) ? "yes" : "no", days_in_month(2, y));
    }

    int total = 0;
    for (int m = 1; m <= 12; m++) {
        total += days_in_month(m, 2026);
    }
    printf("days in 2026: %d\n", total);
    return 0;
}
text
1900: leap no, February has 28 days
2000: leap yes, February has 29 days
2024: leap yes, February has 29 days
2026: leap no, February has 28 days
days in 2026: 365

Things to notice:

  • The leap-year rule is one expression. && binds more tightly than ||, but the parentheses make the structure obvious to a reader, which matters more than saving keystrokes.
  • In days_in_month, the cases 4, 6, 9 and 11 are stacked with no statements between them: that is intentional fall-through, and the compiler does not warn about empty cases. Every path ends in return, so no break is needed.
  • default handles every month not listed. A real program would also reject months outside 1–12 instead of quietly answering 31; robust functions check their inputs, or document that the caller must.

Euclid's algorithm, two ways

The greatest common divisor of two numbers is one of the oldest algorithms on record, described in Book VII of Euclid's Elements: replace the pair (a, b) by (b, a mod b) until b is zero. It translates directly into a loop, or into a recursive function that calls itself:

c
#include <stdio.h>

/* Euclid's algorithm, written two ways. */
unsigned gcd_loop(unsigned a, unsigned b) {
    while (b != 0) {
        unsigned r = a % b;
        a = b;
        b = r;
    }
    return a;
}

unsigned gcd_recursive(unsigned a, unsigned b) {
    if (b == 0) {
        return a;
    }
    return gcd_recursive(b, a % b);
}

unsigned lcm(unsigned a, unsigned b) {
    return a / gcd_loop(a, b) * b;    /* divide first, so the product stays small */
}

int main(void) {
    printf("gcd(1071, 462) = %u\n", gcd_loop(1071, 462));
    printf("gcd(1071, 462) = %u (recursive)\n", gcd_recursive(1071, 462));
    printf("lcm(4, 6) = %u\n", lcm(4, 6));

    /* Two gears turn together; after how many teeth do they line up again? */
    printf("gears of 12 and 18 teeth realign after %u teeth\n", lcm(12, 18));
    return 0;
}
text
gcd(1071, 462) = 21
gcd(1071, 462) = 21 (recursive)
lcm(4, 6) = 12
gears of 12 and 18 teeth realign after 36 teeth

Both versions are correct; the loop is what most C programmers would write. Each recursive call uses a new stack frame for its parameters and return address (the assembly course shows these frames instruction by instruction), so recursion that goes very deep, say a million levels, overflows the stack, which on Linux is typically 8 MB for the main thread. Euclid's algorithm needs only a few dozen steps even for 64-bit numbers, so either version is safe here: Gabriel Lamé showed in 1844 that the number of division steps is never more than five times the number of decimal digits in the smaller number, and the slowest inputs are neighbouring Fibonacci numbers. In lcm, dividing before multiplying keeps the intermediate value small, a habit worth having whenever integer overflow is possible.

Pass by value

C passes every argument by value: the function receives a copy, and changing a parameter changes only the copy. In gcd_loop, the assignments to a and b do not affect the caller's variables. To let a function change a caller's variable, C passes the variable's address instead, which is exactly what pointers, in the next lesson, are for.

Example— The Luhn checksum

Payment card numbers, many national identity numbers and the IMEI numbers of mobile phones end in a check digit computed with the Luhn algorithm. It catches every single mistyped digit and most swaps of two neighbouring digits. This function peels digits off the right-hand end with % 10 and / 10, doubling every second one:

c
#include <stdbool.h>
#include <stdio.h>

/* The Luhn checksum, used by payment card and many identity numbers:
   double every second digit from the right, subtract 9 from results over 9,
   and the total must be a multiple of 10. */
bool luhn_valid(unsigned long long number) {
    int sum = 0;
    bool double_it = false;
    while (number > 0) {
        int digit = (int)(number % 10);
        number /= 10;
        if (double_it) {
            digit *= 2;
            if (digit > 9) {
                digit -= 9;
            }
        }
        sum += digit;
        double_it = !double_it;
    }
    return sum % 10 == 0;
}

int main(void) {
    unsigned long long tests[] = {31415926539ULL, 31415926535ULL, 20261119000ULL};
    for (int i = 0; i < 3; i++) {
        printf("%llu: %s\n", tests[i], luhn_valid(tests[i]) ? "valid" : "invalid");
    }
    return 0;
}
text
31415926539: valid
31415926535: invalid
20261119000: valid

The bool double_it flips on every iteration with !, a common way to alternate. The numbers are unsigned long long (at least 64 bits), written with the ULL suffix so that the constants have that type too, and printed with %llu. The cast (int)(number % 10) tells the reader, and the compiler, that narrowing a remainder from 0 to 9 into an int is intended.

IntuitionH

Scope, lifetime and static

Every variable in C has a scope, the part of the program where its name is visible, and a storage duration, how long its memory exists.

  • A variable declared inside a block (between braces) has block scope and, normally, automatic storage: it is created when execution enters the block and destroyed when it leaves. Function parameters behave the same way.
  • A variable declared outside every function has file scope and static storage: it exists for the whole run of the program. If it is not marked static, other files can refer to it too (it has external linkage), which is why such "global variables" are used sparingly.
  • The keyword static changes things in two different ways depending on where it appears. Inside a function, it gives a local variable static storage: it is initialised once and keeps its value between calls. At file level, it gives a variable or function internal linkage: it becomes private to its file.
c
#include <stdio.h>

/* A static local variable keeps its value between calls. */
int next_ticket(void) {
    static int counter = 100;   /* initialised once, before the program starts */
    counter++;
    return counter;
}

/* static at file level: visible only in this file (internal linkage). */
static int calls = 0;

void greet(const char *name) {
    calls++;
    printf("Habari, %s! (call %d)\n", name, calls);
}

int main(void) {
    printf("ticket %d\n", next_ticket());
    printf("ticket %d\n", next_ticket());
    printf("ticket %d\n", next_ticket());

    greet("Amani");
    greet("Wanjiru");

    int x = 1;
    {
        int x = 2;              /* a new variable in an inner block hides the outer one */
        printf("inner x = %d\n", x);
    }
    printf("outer x = %d\n", x);

    for (int i = 0; i < 10; i++) {
        if (i % 2 == 0) {
            continue;           /* skip even numbers */
        }
        if (i > 7) {
            break;              /* stop the loop entirely */
        }
        printf("%d ", i);
    }
    printf("\n");

    int n = 0;
    do {
        n++;                    /* a do-while body always runs at least once */
    } while (n < 0);
    printf("n = %d\n", n);
    return 0;
}
text
ticket 101
ticket 102
ticket 103
Habari, Amani! (call 1)
Habari, Wanjiru! (call 2)
inner x = 2
outer x = 1
1 3 5 7 
n = 1

next_ticket remembers its counter between calls, the classic use of a static local. (Hidden state like this makes functions harder to test and unsafe to call from several threads at once, so use it with care.) The const char *name parameter is a string; lesson 5 explains the notation. The inner x shadows the outer one only inside its braces; legal, but confusing, and -Wshadow will warn about it if you enable it. The loop shows continue skipping even numbers and break stopping at 9, and the do-while runs its body once even though its condition is false from the start.

The one good goto

C has goto, and most of the time you should not use it. The exception that experienced C programmers accept, and that you will see throughout the Linux kernel, is cleanup on error: a function acquires several resources, and if any step fails it must release the earlier ones in reverse order. Jumping forward to a chain of labels keeps the cleanup in one place:

c
int process(const char *path) {
    int result = -1;
    FILE *f = fopen(path, "r");
    if (f == NULL) goto out;
    char *buffer = malloc(4096);
    if (buffer == NULL) goto close_file;

    /* ... work that may also 'goto free_buffer' on failure ... */
    result = 0;

    free(buffer);
close_file:
    fclose(f);
out:
    return result;
}

Each label undoes one acquisition, and every failure jumps to the label that releases exactly what was acquired so far.

ExplanationH

Designing functions the C way

Without classes, modules or exceptions, C programmers lean on a few conventions to keep functions manageable. You will see them in almost every well-run C code base:

  • One job per function, named for it. days_in_month and is_leap_year are easy to test because each answers one question. A function that parses, validates, computes and prints is hard to test and hard to reuse. Long functions are not forbidden, but a function that needs a comment before every paragraph is usually several functions.
  • Report errors through the return value. C has no exceptions. The common pattern is to return a status (0 for success, a negative number or an error code for failure) and to pass results back through pointer parameters, which the next lesson introduces. Functions that return a pointer use NULL for failure. Whatever you choose, apply it consistently, and always check the result at the call site.
  • Keep helpers private. Mark every function that is not part of a file's public interface static. The compiler can then inline or remove it freely, and nobody else can come to depend on it.
  • State preconditions. If a function requires month to be between 1 and 12, say so in a comment, and check it with assert (lesson 9) in debug builds.
  • Prefer loops to deep recursion. Recursion is elegant for naturally recursive structures such as trees, but C makes no promise to turn tail calls into loops (optimising compilers often do, but only as an optimisation), and the stack is limited. When the depth depends on input size, iterate.
  • Make inputs const. A parameter such as const char *name promises that the function will not modify what it points to. It documents intent and lets the compiler catch accidents.

These habits matter more in C than in most languages, because the language itself enforces so little. Good C is mostly the result of disciplined conventions applied every day.

Common misconceptionsH

Common mistakes

Misconception

Writing = for ==. if (x = 5) assigns 5 to x and is always true. GCC warns (suggest parentheses around assignment used as truth value) under -Wall. Some programmers write constants first (if (5 == x)) so that the mistake fails to compile; with warnings on, that habit is unnecessary.

Misconception

Forgetting break in a switch. Without it, execution falls into the next case. With -Wextra, GCC warns this statement may fall through. When fall-through is intended, say so with a comment or C23's [[fallthrough]];.

Misconception

Writing int f() and thinking it means "no parameters". Until C23, empty parentheses in a declaration meant "unspecified parameters", and the compiler would not check calls. Write int f(void). (C23 finally makes () mean the same as (void).)

Misconception

Expecting a function to change its argument. void reset(int n) { n = 0; } changes only its own copy of n. Pass a pointer, or return the new value.

Misconception

A semicolon after the condition. for (int i = 0; i < 10; i++); and if (ready); have empty bodies: the block that follows runs once, unconditionally. GCC warns about the if version with -Wextra (-Wempty-body).

Exercises

Exercises

All outputs below were checked by compiling and running the code with GCC.

1. Control flow and functions

Warm-upComputational

Using the lesson's days_in_month, what is days_in_month(2, 2100)?

2. Control flow and functions

Warm-upComputational

What does gcd_recursive(84, 36) return?

3. Control flow and functions

CoreComputational

How many times in total is gcd_recursive called (counting the first call) to compute gcd_recursive(1071, 462)?

4. Control flow and functions

CoreComputational

What does this loop print? (Separate the numbers with single spaces.)

for (int i = 0; i < 10; i++) {
    if (i % 3 == 0) continue;
    if (i > 7) break;
    printf("%d ", i);
}

5. Control flow and functions

CoreComputational

With int x = 2;, what does this print? (Separate the words with single spaces.)

switch (x) {
case 1: printf("one ");
case 2: printf("two ");
case 3: printf("three ");
default: printf("other ");
}

6. Control flow and functions

CoreComputational

What does this program print?

void bump(int n) { n = n + 10; printf("inside: %d\n", n); }

int main(void) {
    int n = 5;
    bump(n);
    printf("outside: %d\n", n);
    return 0;
}
Choose one

7. Control flow and functions

CoreComputational

In the lesson's program, next_ticket starts with static int counter = 100;. If main called it a fourth time, what would that call return?

Further reading and resources