Foundations of ComputingVol. 1 · Part I
0 / 0

Shelves / Foundations of Computing

CS·02

Programming Fundamentals & Paradigms

What a program is, how source becomes execution, and how six languages answer the same basic questions about values, memory, errors and abstraction.

83 topics · ~117 min read · 46-question quiz
Updated Suggest a correction

Start here: thinking like a programmer

Every program, in every language, is built from the same small set of ideas: values of different types, variables that hold them, expressions that compute new values, decisions, repetition, functions that package steps under a name, and collections that hold many values. This section explains each in plain terms, with examples you can trace by hand. The rest of the chapter then goes much deeper into each one, across six languages.

Values and types in everyday terms

A value is a single piece of data: the number 42, the price 120.50, the word "biryani", the answer true. A type says what kind of value something is, and therefore what you can do with it. You can add two numbers and you can join two words, but "add 3 to the word biryani" makes no sense, and types are how the language notices.

Type (common name) Holds Examples Typical operations
Integer Whole numbers 0, 42, -7 + - * /, comparison
Floating point (float, double) Numbers with a fractional part 3.14, -0.5, 116.83 Arithmetic (approximate: chapter 6)
Boolean Truth values true, false and, or, not
Character One letter or symbol 'A', '?' Compare, convert to a number
String Text: a sequence of characters "Hello", "" (empty) Join, measure length, search

Some languages make you declare the type (int count = 0; in C and Java); others infer it from the value (count = 0 in Python, count := 0 in Go, let count = 0; in Rust). Either way, every value has a type.

Variables: labelled boxes

A variable is a named box that holds a value. You assign a value with =, and you can replace it later:

Python
lunches = 5          # create a box named lunches holding 5
lunches = lunches - 1   # read the box (5), subtract 1, put the result (4) back
price = 120.0
total = lunches * price  # 4 * 120.0 = 480.0
after each line runs lunches54 price120.0 total480.0 total = lunches * price: read both boxes, multiply, store the result
Variables as labelled boxes. Assignment computes the value on the right first, then puts it into the box named on the left, replacing what was there. Reading a variable copies its current value out without changing it.

Two things confuse almost every beginner, so settle them now:

  • = means "store", not "is equal to". lunches = lunches - 1 is nonsense in algebra but perfectly sensible in code: compute the right-hand side using the current value, then store the result. Testing equality uses == (in most languages).
  • A variable holds its value until you change it. total was computed from lunches once; if you later change lunches, total does not update itself. It's a box with a number in it, not a formula like a spreadsheet cell.

A constant is a variable you promise never to change (final in Java, const in C, C++, Go, Zig and Rust); the compiler holds you to the promise.

Expressions: how a line gets evaluated

An expression is anything that produces a value: 2 + 3, price * 1.18, count > 0, len(name). The computer evaluates it in a fixed order, like school arithmetic: parentheses first, then multiplication and division, then addition and subtraction, left to right among equals (operator precedence).

2 + 3 * 4 → 3 * 4 first → 2 + 12 → 14. (2 + 3) * 4 → 20.

Division deserves special attention, because languages differ:

Terminal
$ python3 -c "print(7 / 2, 7 // 2, 7 % 2, -7 // 2, -7 % 2)"
3.5 3 1 -4 1
$ java Div          # prints 7/2, 7%2, -7/2, -7%2, 7/2.0
3 1 -3 -1 3.5
  • In Java, C, C++, Go and Rust, dividing two integers gives an integer: 7 / 2 is 3 (the fraction is thrown away). Write 7 / 2.0 to get 3.5. Python 3's / always gives a float; // is integer ("floor") division.
  • % is the remainder (modulo): 7 % 2 is 1. It's how you test "is n even?" (n % 2 == 0) or "is n a multiple of 3?" (n % 3 == 0).
  • With negative numbers, languages disagree: Python rounds -7 // 2 down to -4 (and makes -7 % 2 equal 1), while Java and C round towards zero (-3 and -1). Chapter 2's operator section and chapter 6 explain why; for now, know that it differs.

Comparison expressions produce booleans: == (equal), != (not equal), <, <=, >, >=. Logical operators combine them: and/&& (both true), or/|| (at least one true), not/! (the opposite).

Decisions: if, else if, else

A program chooses between paths with if:

Python
if count == 0:
    print("no lunches booked")
elif count == 1:
    print("one lunch booked")
else:
    print(f"{count} lunches booked")

The conditions are checked top to bottom, and only the first true branch runs. That's why order matters: in FizzBuzz below, the "multiple of 15" test must come before "multiple of 3", or 15 would print "Fizz".

Repetition: loops

Loops repeat a block. The two basic forms:

  • A while loop repeats as long as a condition is true: while seats_left > 0: …. Something inside must eventually make the condition false, or the loop runs forever (an infinite loop; stop it with Ctrl+C).
  • A for loop repeats once per item in a sequence: for name in names: …, or once per number in a range: for i in range(5) gives 0, 1, 2, 3, 4 (five numbers, starting at 0, stopping before 5).

Trace this loop by hand before reading the table:

Python
total = 0
for i in range(1, 5):      # i takes the values 1, 2, 3, 4
    total = total + i * i
print(total)
Iteration i i * i total after
(before) 0
1 1 1 1
2 2 4 5
3 3 9 14
4 4 16 30

It prints 30. If you expected 55 (1 + 4 + 9 + 16 + 25), you've met the most common bug in programming: the off-by-one error. Ranges usually include the start and exclude the end. When writing a loop, always check the first and last iterations explicitly.

Functions: recipes with inputs and outputs

A function packages steps under a name so you can reuse them. It takes parameters (inputs) and usually returns a result (output):

Python
def price_with_gst(price, rate):
    tax = price * rate
    return price + tax

print(price_with_gst(120, 0.05))   # 126.0
print(price_with_gst(200, 0.18))   # 236.0
  • Defining a function (def …) doesn't run it; calling it (price_with_gst(120, 0.05)) does.
  • When called, the arguments 120 and 0.05 are given the parameter names price and rate for the duration of the call.
  • return sends a value back to the caller and ends the function.
  • Variables created inside a function (tax) are local: they exist only during that call and can't be seen outside. This keeps functions independent, so you can understand each one on its own.

Good functions do one thing, have a name that says what, and are short enough to read at a glance. Breaking a problem into functions is how large programs stay understandable.

Collections: many values under one name

Programs constantly deal with many values. The two collections you'll use most:

  • A list (array, vector, slice) holds values in order, numbered by position starting at 0: menu = ["biryani", "dal", "paneer"], so menu[0] is "biryani" and menu[2] is "paneer". len(menu) is 3; menu[3] is an error (chapter 1's out-of-bounds message).
  • A dictionary (map, hash map) holds key → value pairs, looked up by key rather than position: prices = {"biryani": 180, "dal": 90}, so prices["dal"] is 90.

Chapter 3 explains how these are built inside the computer and why some operations on them are fast and others slow.

From a problem to a program

Writing code is the second step. The first is working out what the program must do, in plain words. A method that works at every level of experience:

  1. Restate the problem precisely, including inputs, outputs and unusual cases. ("Given a list of exam marks, print each student's grade. Marks are 0–100. What if the list is empty? What if a mark is 101?")
  2. Work a small example by hand. If you can't solve it on paper, you can't program it.
  3. Write the steps in plain language (pseudocode), then refine them until each step is obviously one or two lines of code.
  4. Write the code, one small piece at a time, running it after each piece.
  5. Test with normal cases, edge cases (empty input, the smallest and largest values) and invalid input.

Three classic exercises, solved

Try each exercise yourself before reading the solutions. They're small, but between them they use every idea above.

  1. FizzBuzz. Print the numbers 1 to 15, but print "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for multiples of both.
  2. Largest. Write a function that returns the largest number in a list, without using a built-in max. Decide what it should do for an empty list.
  3. Vowels. Write a function that counts the vowels (a, e, i, o, u) in a sentence, ignoring upper/lower case.
# Exercise 1: FizzBuzz for 1..15
for n in range(1, 16):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)

# Exercise 2: the largest number in a list (without using max)
def largest(numbers):
    if not numbers:
        return None                     # an empty list has no largest number
    best = numbers[0]
    for x in numbers[1:]:
        if x > best:
            best = x
    return best

print(largest([12, 7, 31, 4]), largest([-5, -2, -9]), largest([]))

# Exercise 3: count the vowels in a sentence
def count_vowels(text):
    count = 0
    for ch in text.lower():
        if ch in "aeiou":
            count += 1
    return count

print(count_vowels("Hyderabadi Biryani"))
Text
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz      (one per line in the real output)
31 -2 None          ← Java prints null, C prints (empty)
7

Points worth noticing in the solutions:

  • Largest starts from the first element, not from 0: starting from 0 would wrongly return 0 for a list of negative numbers like [-5, -2, -9]. That's an edge case worth a test.
  • Each language handles "no answer" differently: Python returns None, Java returns null (so the return type is Integer, an object, rather than int), and C returns a success flag and writes the answer through a pointer (chapter 2 explains pointers). Chapter 2's error-handling section compares these styles.
  • Vowels converts to lower case once, so "A" and "a" both count. "Hyderabadi Biryani" has 7 vowels (y isn't counted, by the exercise's definition).

Common beginner mistakes

Mistake Example Fix
= instead of == in a condition if (count = 0) in C assigns 0 and is always false Use ==; enable compiler warnings (-Wall)
Off by one for i in range(1, 5) misses 5 Check first and last iterations by hand
Integer division average = total / count with integers drops the fraction Convert to floating point first
Using a variable before giving it a value total = total + x with no total = 0 first Initialise before the loop
Forgetting the empty case numbers[0] on an empty list crashes Check for empty input explicitly
Changing a list while looping over it Removing items inside for x in items skips elements Build a new list instead
Copy-pasted code drifting apart Two nearly identical blocks, one later fixed Make a function

How deep to go in programming fundamentals

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere and L4 in the labs at the end, which is the foundation every later volume builds on.

Level What you can do
L1 Name the parts of a program: values, variables, expressions, statements, functions, modules
L2 Write correct, idiomatic code in at least two of C, C++, Java, Rust, Zig, Go: control flow, functions, errors, tests, I/O
L3 Explain what each construct compiles to: stack frames for calls, how values are copied or shared, how errors propagate, what a module boundary means to the linker
L4 Diagnose aliasing bugs, stack overflows, swallowed errors, resource leaks and serialization incompatibilities from symptoms
L5 Choose value, reference or ownership semantics, error-handling style and paradigm for a given problem and team
L6 Keep a codebase's fundamentals sound for years: API compatibility, error contracts, serialization versioning, safe refactoring

From source code to a running program

Every language in this book answers one question differently: what happens between the text you type and the instructions the CPU executes? Most other differences follow from that answer. These include speed, safety, startup time, how errors show up, and how much you can see of the machine.

Source, translation and execution

A CPU understands only machine code: binary-encoded instructions for its instruction set (x86-64, ARM64, RISC-V). Everything else is a translation strategy.

  • Ahead-of-time (AOT) compilation translates the whole program to machine code before it runs. C, C++, Rust, Zig and Go work this way. The output is a native executable for one OS and CPU pair.
  • Interpretation reads the program (or a tree or bytecode form of it) and performs each operation in a loop written in another language. CPython and early JavaScript engines work this way.
  • Bytecode plus a virtual machine compiles to a portable instruction set for an imaginary machine. A VM then interprets that bytecode and, for hot code, compiles it to native code at run time (JIT, just-in-time). Java works this way: javac emits .class bytecode, and the JVM interprets it, profiles it, and JIT-compiles hot methods with its C1 and C2 compilers.
AHEAD-OF-TIME (C · C++ · Rust · Zig · Go) source compilerfront→IR→back object files.o / .obj linker native exeELF / PE / Mach-O OS loader → CPU BYTECODE + VM (Java) .java javac .class / .jarbytecode JVM (at run time) interpreter profilerhot methods JIT: C1 → C2native code, deoptimize if wrong
Translation pipelines. The five native languages finish translation before the program starts; Java finishes it while the program runs.

Neither model is better in general. Each trades something:

Property AOT native (C, C++, Rust, Zig, Go) Bytecode + JIT (Java)
Startup Instant: code is ready Slower: class loading, interpretation, warm-up
Peak speed Fixed at compile time Can exceed AOT on hot paths, because the JIT sees real profiles
Portability Recompile per target Same .jar runs on any JVM
Distribution One binary (Go and Zig link statically by default) Needs a JVM, or GraalVM native-image to go AOT
Optimisation info Static analysis only (plus optional PGO) Live profiles, can speculate and deoptimise
Introspection Debug info if kept Rich reflection, JFR, attachable agents

Compilation units, headers and the build

The compiler rarely sees your whole program at once. It processes translation units and the linker stitches them together.

  • C and C++: each .c or .cpp file, after the preprocessor has pasted in its #included headers, is one translation unit. A header declares (int add(int, int);) and exactly one .c file defines. The linker matches symbols by name. This is why C has the one-definition rule pains, include guards, and slow builds when one header changes. C++20 modules (import std; in C++23) replace textual inclusion with compiled interfaces, but tooling support is still uneven.
  • Rust: the unit is the crate (a library or binary). Modules inside a crate are compiled together, and rustc splits a crate into parallel codegen units itself.
  • Go: the unit is the package (a directory). Imports are compiled export data, so there are no headers. Go was designed for fast builds. Unused imports are compile errors so the dependency graph stays honest.
  • Zig: every file is a struct. @import("foo.zig") returns it. The compiler analyses lazily from main outward, so code that is never referenced is never even type-checked.
  • Java: each .java file holds one public top-level class and compiles to a .class file. Linking happens lazily at run time when the JVM resolves a class reference.
Text
C:     a.c + a.h ──cc -c──▶ a.o ─┐
       b.c + a.h ──cc -c──▶ b.o ─┴─ld──▶ app       (symbols matched by name)
Rust:  src/**.rs ─────rustc (crate)──────▶ app      (whole crate is one unit)
Go:    pkg dirs ─────go build (per pkg)──▶ app      (static binary by default)
Java:  *.java ──javac──▶ *.class ──jar──▶ app.jar   (linked lazily by the JVM)

Values, variables and constants

Values, types and representation

A value is a piece of data: the integer 42, the string "hi", a point (3, 4). A type is a set of values plus the operations allowed on them. To the hardware, everything is bits. The type tells the compiler how many bits there are, how to interpret them, and which instructions to emit. 0x41 in one byte is 65 as a u8, the character 'A' in ASCII, and part of a float if read as an f32.

Every language here is statically typed: the type of every expression is known at compile time. They differ in how much the compiler checks and how much it infers:

C C++ Java Rust Zig Go
Local inference auto (C23) auto var (10+) let x = … everywhere const x = … x := …
Implicit numeric conversions Many (promotions) Many Widening only None Only lossless coercions None
Null in ordinary pointers/references Yes Yes (pointers) Yes (all references) No (Option<T>) No (?*T) Yes (nil)
Sized integer names int32_t std::int32_t int (always 32) i32 i32, also u7… int32

Variables: names, bindings and storage

A variable binds a name to a storage location that holds a value. Keep three ideas separate:

  1. Name: what you write in code. It exists only at compile time, unless debug info keeps it.
  2. Location: where the bits live. That can be a register, a stack slot, the heap, or the static data segment.
  3. Value: the bits currently stored there.

C's terminology is useful everywhere. An lvalue designates a location (it can appear on the left of =). An rvalue is just a value (x + 1). C++ refines this into lvalue, xvalue and prvalue for move semantics.

Storage duration says how long the location exists:

  • Automatic: lives for a block or function call, usually on the stack. Function locals work this way.
  • Static: lives for the whole program. Globals, C static locals, Java static fields (per class loader) and Rust static items work this way.
  • Dynamic: lives from an explicit allocation until it is freed or collected: malloc/free, new, Box::new, allocator.create, or anything a GC manages.
  • Thread-local: one copy per thread. C has _Thread_local (thread_local in C23), C++ has thread_local, Java has ThreadLocal, Rust has thread_local!, and Zig has threadlocal var. Go has none on purpose, because goroutines aren't threads.
#include <stdio.h>
#include <stdlib.h>

int counter = 0;              // static storage, external linkage

void f(void) {
    static int calls = 0;     // static storage, block scope: survives calls
    int local = 5;            // automatic: dies when f returns
    int *heap = malloc(sizeof *heap);  // dynamic: lives until free()
    *heap = local + ++calls;
    printf("%d\n", *heap);
    free(heap);
}

Initialization rules

What a variable holds before you assign it is one of the clearest differences between the six languages:

Language Uninitialised local Rule
C Indeterminate value; reading it is often UB Initialise everything yourself
C++ Same as C for scalars; class types run their constructor. C++26 makes such reads "erroneous behaviour" rather than UB Use {} value-initialisation
Java Compile error (definite assignment analysis) Fields default to 0, false or null
Rust Compile error if read before assignment let x; if c { x = 1 } else { x = 2 } is fine
Zig Must write an initialiser; = undefined is explicit, and Debug builds fill it with 0xAA Reading undefined is illegal behaviour
Go Always the zero value: 0, "", nil, a zeroed struct Design types so the zero value is useful

Go's "make the zero value useful" is a design philosophy. A zero sync.Mutex is an unlocked mutex, and a zero bytes.Buffer is an empty buffer ready to use. Zig makes uninitialised memory visible in the source instead of forbidding it, because sometimes you really don't want to pay for zeroing a 64 KB buffer.

Constants and compile-time evaluation

"Constant" means at least three different things. Keep them separate:

  1. Immutable binding: this name can't be reassigned (Java final, Rust let, Zig const, JavaScript const).
  2. Read-only view: you can't modify through this pointer, but someone else might (C/C++ const T*, Rust &T usually).
  3. Compile-time constant: the value is known while compiling and can size arrays, select types or be folded away.
#define BUF 256                    // textual macro: no type, no scope
enum { MAX_USERS = 100 };          // classic integer constant trick
static const double PI = 3.14159;  // read-only object, not always a constant expression in C
constexpr int N = 16;              // C23: a real compile-time constant
int arr[N];

The spectrum of compile-time power runs: C macros (text substitution), C++ constexpr/templates (a second, functional language inside C++), Rust const fn plus macros (restricted but growing), and Zig comptime, where ordinary Zig code runs at compile time and types are first-class values. Go deliberately limits this to constants and generics.

Scope, lifetime and shadowing

Scope is where a name is visible. That's a compile-time, textual property. Lifetime is when the storage exists. That's a run-time property. They often coincide for locals but differ in important cases. A C static local has block scope but program lifetime. A Go local whose address escapes outlives its scope. A Java object outlives every name that pointed to it until the GC notices.

Lexical (static) scoping means a name refers to the nearest enclosing declaration in the source text. All six languages use it, and so do JavaScript and Python. Dynamic scoping (old Lisps, Bash variables) resolves names by the call stack, which is why it's rare now.

Shadowing declares a new variable with the same name in an inner scope (or, in Rust, the same scope):

Rust
let input = "42";               // &str
let input: i32 = input.parse().unwrap(); // new binding, new type, same name

Rust encourages this for transformations. Go allows shadowing, and it is a classic bug source with :=: err := … inside an if creates a new err, and the outer one stays nil. Java forbids shadowing a local with another local. Zig forbids shadowing entirely ("local shadows declaration"), so names are never ambiguous.

Expressions, statements and operators

Expressions versus statements

An expression produces a value: a + b, f(x), x > 3. A statement performs an action and produces nothing: a declaration, return, a loop. Languages differ in how much is an expression.

  • C, C++, Java, Go are statement-oriented. if is a statement, so you need the ternary c ? a : b for a conditional value. Go has no ternary at all, by design.
  • Rust and Zig are expression-oriented. Blocks, if, match/switch and even loop produce values.
let grade = if score >= 90 { 'A' } else if score >= 80 { 'B' } else { 'C' };

let parsed = match s.parse::<i32>() {
    Ok(n) => n,
    Err(_) => 0,
};

let mut i = 0;
let first_big = loop {          // `loop` can yield a value with `break`
    if v[i] > 100 { break v[i]; }
    i += 1;
};
// the last expression without `;` is the block's value
let area = { let w = 3; let h = 4; w * h };

Arithmetic, division and the overflow question

Integer arithmetic looks universal until you hit the edges. Two edges matter most: division of negatives and overflow.

Division. All six languages truncate integer division toward zero: -7 / 2 == -3. The remainder takes the sign of the dividend: -7 % 2 == -1. Python and Ruby use floor division instead (-7 // 2 == -4, -7 % 2 == 1). When you need a non-negative modulus, for example when computing a ring-buffer index or a weekday, use:

  • Java: Math.floorMod(-7, 2) == 1
  • Rust: (-7i32).rem_euclid(2) == 1
  • Zig: @mod(-7, 2) == 1. Zig refuses plain / and % on signed runtime integers and makes you choose @divTrunc, @divFloor, @rem or @mod.
  • C, C++, Go: ((a % n) + n) % n

Overflow. What happens with i32::MAX + 1?

Language Signed overflow Unsigned overflow Tools
C Undefined behaviour Wraps mod 2ⁿ __builtin_add_overflow, C23 ckd_add
C++ Undefined behaviour Wraps mod 2ⁿ same builtins; C++26 std::add_sat
Java Wraps silently (no unsigned types; Integer.toUnsignedString etc.) Math.addExact throws
Rust Panics in debug; wraps in release (unless overflow-checks = true) Same checked_add, wrapping_add, saturating_add, overflowing_add
Zig Illegal behaviour: panics in Debug/ReleaseSafe, UB in ReleaseFast Same +% wrap, +| saturate, @addWithOverflow
Go Wraps (defined) Wraps math/bits.Add64 for carries

Precedence, associativity and evaluation order

Precedence decides grouping (a + b * c is a + (b * c)). Associativity decides grouping among equals (a - b - c is (a - b) - c, and a = b = c is a = (b = c)). Neither says in which order the operands run. That is a third rule, and here the languages genuinely differ:

  • Java: left to right, always. In f() + g(), f runs first. Arguments are evaluated left to right.
  • Rust: operands and arguments are evaluated left to right.
  • Go: function calls, method calls and channel operations are evaluated in lexical left-to-right order. The order of other operands relative to those calls is unspecified.
  • C: the order of operands of most operators and of function arguments is unspecified. f() + g() may call g first. i = i++ + 1; is undefined because it modifies i twice without a sequence point.
  • C++17 tightened the rules. <<, >>, ., ->, [] and assignments now have defined order, but function arguments are still indeterminately sequenced.

The rule that keeps you safe in every language: never depend on evaluation order for side effects in one expression. Split it into statements.

Logical, bitwise and comparison operators

  • Short-circuit: && and || (and/or in Zig) evaluate the right side only if needed. Code like p != NULL && p->x > 0 relies on this.
  • Bitwise & | ^ ~ << >> operate on bits (chapter 6 covers them in depth). Some traps: in C, x & 1 == 0 parses as x & (1 == 0), because == binds tighter than &. Rust and Go fixed this precedence. Shifting a 32-bit value by 32 or more is UB in C and C++, a panic in debug Rust, and a compile error or panic in Zig. Go defines it, and the result is 0. Java masks the shift count (x << 33 equals x << 1 for int). Right shift of negative numbers is arithmetic in Java (>>), which also has a logical shift >>>. Rust, Go and Zig choose by signedness. C++20 defines it as arithmetic.
  • Equality: == compares values for primitives in all six. For objects it diverges. In Java, == on objects compares references (identity), so use .equals() for contents. That's why new String("a") == new String("a") is false. Rust == calls PartialEq::eq, which compares contents. Go == compares structs field by field, but is a compile error on slices, maps and functions. C compares pointer addresses, and C++ calls operator==.

Conversions and casting

Implicit conversions are where C bites hardest. In if (-1 < sizeof(int)), the -1 is converted to size_t, an enormous unsigned number, so the comparison is false. The newer languages removed nearly all implicit numeric conversions:

unsigned u = 1;
int i = -1;
if (i < u) puts("never printed");   // i converted to unsigned: 4294967295 < 1 is false
char c = 300;                        // implementation-defined truncation, no error
double d = 3.9; int n = (int)d;      // 3: truncates toward zero

Control flow

Conditionals and multi-way branches

if/else is universal. The differences are in multi-way branches: switch and its descendants.

Fallthrough by default? Must be exhaustive? Patterns?
C/C++ switch Yes (forget break, get a bug) No (-Wswitch warns on enums) Integer constants only
Java switch (classic :) Yes No Constants, strings, enums
Java switch (arrow ->, 14+) No Yes when used as an expression Type and record patterns, guards (21+)
Go switch No (fallthrough keyword opts in) No Any expression; type switches
Rust match No Yes (compile error) Full destructuring patterns, guards, bindings
Zig switch No Yes (or else) Values, ranges, tagged-union payloads

Exhaustiveness is the property that the compiler proves every case is handled. When you add a new enum variant, every match that forgot it becomes a compile error. That turns "update all call sites" from a code-review hope into a compiler guarantee.

enum Shape { Circle { r: f64 }, Rect { w: f64, h: f64 }, Tri(f64, f64, f64) }

fn area(s: &Shape) -> f64 {
    match s {
        Shape::Circle { r } => std::f64::consts::PI * r * r,
        Shape::Rect { w, h } if w == h => w * w,     // guard
        Shape::Rect { w, h } => w * h,
        Shape::Tri(a, b, c) => {                     // Heron's formula
            let p = (a + b + c) / 2.0;
            (p * (p - a) * (p - b) * (p - c)).sqrt()
        }
    }   // add a variant to Shape and this stops compiling
}

Loops and iteration

Every loop is a variation on "test, body, step." The languages differ in syntax and in how they iterate collections:

  • C: for (init; cond; step), while, do … while. You iterate collections by index or pointer.
  • C++: the same, plus range-for for (auto& x : v), which works on anything with begin() and end(). C++20 adds ranges and views for lazy pipelines.
  • Java: the classic for, plus enhanced-for over any Iterable, plus Streams (chapter 37 of the roadmap).
  • Rust: loop, while, for x in iter. for only works with iterators; there is no C-style for. Ranges are 0..n (exclusive) and 0..=n (inclusive).
  • Zig: while (cond) : (step), for (slice) |item|, for (0..n) |i|, and for (a, b) |x, y| to walk two slices in lockstep. A loop can have an else branch that runs when the loop completes without break.
  • Go: one keyword, for, does everything: for i := 0; i < n; i++, for cond, for {}, and for i, v := range xs. Since Go 1.22 you can range over an integer (for i := range 10), and since 1.23 over iterator functions.
int sum = 0;
for (size_t i = 0; i < n; i++) sum += a[i];
for (const int *p = a; p != a + n; p++) sum += *p;   // pointer walk

Jumps and structured cleanup

Early exits (break, continue, return) are fine. The hard problem is cleanup: releasing a lock, closing a file or freeing memory on every exit path, including errors. Each language has an answer:

Mechanism Languages Runs when
goto cleanup; C You jump to it explicitly. This is the Linux kernel idiom, and a legitimate use of goto
Destructors (RAII) C++, Rust (Drop) The owning object goes out of scope, on any path including exceptions and panics
try/finally, try-with-resources Java The block exits, normally or by exception
defer Go, Zig The function returns in Go; the enclosing block exits in Zig
errdefer Zig The block exits with an error only
int process(const char *path) {
    int rc = -1;
    FILE *f = fopen(path, "r");
    if (!f) goto out;
    char *buf = malloc(4096);
    if (!buf) goto close_file;
    if (fread(buf, 1, 4096, f) == 0) goto free_buf;
    rc = 0;                     // success
free_buf:   free(buf);
close_file: fclose(f);
out:        return rc;          // cleanup in reverse order of acquisition
}

Functions

Anatomy of a function

A function is a named, reusable piece of computation with parameters (formal inputs), a return type, and a body. Its signature (name, parameter types, return type, plus in some languages its error set or throws clause) is its contract with callers.

At the machine level (chapter 7), a call means: put arguments in registers or on the stack as the calling convention dictates (System V AMD64 passes the first six integer arguments in rdi, rsi, rdx, rcx, r8, r9), push the return address, jump, set up a stack frame, run, put the result in rax, tear down the frame, and return. Inlining removes all of that, which is why small functions are usually free in optimised builds.

Parameter passing: value, pointer, reference, move

This is the single most important table in the chapter, because it decides who can see your changes and who pays for copies:

Language Default Other modes
C By value, always. Arrays decay to pointers Pass a pointer to let the callee modify: f(&x)
C++ By value (copy constructor runs) T& reference, const T& read-only, T&& rvalue/move, T* pointer
Java By value, always. For objects, the value copied is the reference No way to pass a variable by reference
Rust By move for non-Copy types; by copy for Copy types (integers, &T) &T shared borrow, &mut T exclusive borrow
Zig By value semantically. The compiler may pass large structs by const pointer, since parameters are immutable *T pointer to modify, *const T
Go By value, always. Slices, maps, channels and interfaces are small headers that point at shared data *T pointer to modify
STACKHEAP caller framelist ● callee frame: f(List p)p ●copy of the reference ArrayList ["a","b"]p.add("b"): caller sees it new ArrayList [ ] dashed: before reassignment orange: after p = new ArrayList<>()
Java is pass-by-value: the callee receives a copy of the reference. Mutating the object is visible to the caller; reassigning the parameter is not.
static void mutate(List<String> p) { p.add("b"); }        // caller sees "b"
static void reassign(List<String> p) { p = new ArrayList<>(); p.add("z"); } // caller sees nothing
static void bump(int n) { n++; }                          // caller's int unchanged

Multiple returns, tuples and out-parameters

Functions often need to return more than one thing, such as a value and an error, or a quotient and a remainder:

  • C: out-parameters (int div(int a, int b, int *rem)), or return a struct.
  • C++: std::pair/std::tuple with structured bindings (auto [q, r] = divmod(7, 2);), or a struct.
  • Java: return a record (record DivMod(int q, int r) {}). Java has no tuples.
  • Rust: tuples (fn divmod(a: i32, b: i32) -> (i32, i32), then let (q, r) = divmod(7, 2);).
  • Zig: anonymous structs or tuples (return .{ q, r };).
  • Go: built-in multiple return values (func divmod(a, b int) (int, int)), the basis of value, err :=.

Overloading, default arguments and variadics

  • Overloading (same name, different parameter types): C++ and Java have it. C has none, though C11 _Generic dispatches on type in macros. Rust, Zig and Go have none, by design: Rust uses traits and Go uses different names (strconv.Itoa and strconv.FormatInt). Overloading complicates type inference and makes "which function is called?" non-obvious.
  • Default arguments: only C++ has them. In the others, you write overloads (Java), builder or Default patterns (Rust ..Default::default()), options structs (Go and Zig: .{ .timeout = 30 } relies on default field values).
  • Variadics: C ... with va_list (no type safety: printf("%d", 3.0) is UB). C++ has variadic templates, which are type-safe. Java has String... args (it's an array). Go has args ...int (a slice). Rust has no variadic functions, so it uses macros (println!, vec!). Zig uses tuples with anytype: std.debug.print("{d} {s}", .{ n, s }).

First-class functions and closures

A language has first-class functions when functions are values: you can store them, pass them and return them. A closure is a function plus the variables it captures from the scope where it was created. How a closure captures (copy or reference) and how long the captured variables live are the key questions.

// C: function pointers only, no captures. Fake a closure with a void* context.
typedef int (*cmp_fn)(const void *, const void *);
int by_value(const void *a, const void *b) { return *(int*)a - *(int*)b; }
qsort(arr, n, sizeof arr[0], by_value);

struct adder { int k; };
int apply(int (*fn)(void *ctx, int), void *ctx, int x) { return fn(ctx, x); }
int add_k(void *ctx, int x) { return ((struct adder*)ctx)->k + x; }

Higher-order functions

A higher-order function takes or returns functions: map, filter, reduce (fold), sort with a comparator, retry wrappers, middleware. They let you separate what to do to each element from how to iterate. In Rust and C++ these compile down to plain loops, because closures are inlined through monomorphisation. In Java the JIT usually inlines small lambdas. In Go, closures called through a function value usually aren't inlined, so tight loops are often written by hand.

Recursion

How recursion works

A function is recursive when it calls itself, directly or through others (mutual recursion). Each call gets its own stack frame holding its parameters, locals and return address, so each level has independent variables. Recursion needs:

  1. A base case that returns without recursing.
  2. Progress: each recursive call moves toward the base case, for example a smaller n or a shorter list.
fact(3) → 3 * fact(2) fact(2) → 2 * fact(1) fact(1) → 1 * fact(0) fact(0) → 1 (base case) push pop & return returns 1returns 1·1 = 1returns 2·1 = 2returns 3·2 = 6
Call stack for fact(3). Frames are pushed on the way down and popped on the way back up, multiplying as they return.

Tail calls and stack depth

A call is a tail call when it's the last thing a function does: return f(x), not return n * f(x). A compiler can then reuse the current frame (tail-call optimisation, TCO), turning recursion into a loop with constant stack. Scheme guarantees TCO, and so do most functional languages. None of the six languages here guarantees it in general, which matters:

  • C and C++: optimisers usually do it at -O2, but nothing guarantees it. Clang offers [[clang::musttail]].
  • Rust: not guaranteed. An become keyword for guaranteed tail calls has been in development.
  • Zig: return @call(.always_tail, f, .{args}) guarantees it or fails to compile.
  • Java: the JVM doesn't do TCO. Deep recursion throws StackOverflowError.
  • Go: no TCO, but goroutine stacks grow (they start at a few kilobytes and are copied to larger ones as needed), so deep recursion runs until the 1 GB default maximum on 64-bit systems.

Default stack sizes matter for recursive algorithms. A Linux main thread usually gets 8 MB (ulimit -s). Rust spawned threads get 2 MB. Java threads usually get 512 KB to 1 MB (-Xss). A recursive DFS over a million-node linked graph will overflow. Convert it to an explicit stack (a Vec or ArrayDeque you push to), which is the standard fix.

// recursive: depth = n, may overflow for large n
fn sum_rec(v: &[i64]) -> i64 {
    match v { [] => 0, [first, rest @ ..] => first + sum_rec(rest) }
}
// accumulator style is a tail call, but Rust won't promise TCO, so write the loop:
fn sum_iter(v: &[i64]) -> i64 { v.iter().sum() }

Recursion versus iteration

Every recursion can be made iterative (with an explicit stack) and vice versa. Choose by clarity first. Recursion is natural for trees, divide-and-conquer and grammars. Iteration is natural for sequences. Switch when depth is unbounded or data-dependent. Memoisation, which caches results of pure recursive calls, turns exponential recursion like naive Fibonacci into linear time. It's the bridge to dynamic programming in chapter 4.

Compound data in the language

Chapter 3 covers data structures as algorithms. Here we look at the building blocks the languages give you: aggregates, strings, sum types and pointers. These decide how data sits in memory.

Arrays, slices and strings

An array is a fixed number of same-typed elements stored contiguously. A slice (or span or view) is a pointer plus a length that refers to part of an array without owning it. The pointer+length pair is one of the most important ideas in systems programming. C lacks it, and the absence of a length is the root of most buffer overflows.

Fixed array Growable array Borrowed view Bounds checked?
C int a[8] (decays to int*) hand-rolled realloc int *p, size_t n No
C++ std::array<int,8> std::vector<int> std::span<int> (20) .at() yes, [] no (hardened modes optional)
Java int[] (heap object with length) ArrayList<Integer> List.subList, Arrays.asList Yes, always (ArrayIndexOutOfBoundsException)
Rust [i32; 8] Vec<i32> &[i32], &mut [i32] Yes (panic); get() returns Option
Zig [8]i32 std.ArrayList(i32) []i32, []const i32 Yes in safe modes
Go [8]int (a value! copied on assignment) slice []int with append slice s[lo:hi] Yes (panic)

Strings are where the six languages disagree most. The question is what a "character" is. Chapter 6 explains Unicode properly. The short version: a Unicode code point (like U+00E9 é) is encoded as 1 to 4 bytes in UTF-8, or 1 to 2 16-bit units in UTF-16. A user-perceived character, a grapheme cluster such as 👍🏽, may be several code points.

Type Encoding Mutable? len means
C char* ending in '\0' Whatever bytes you put in Yes strlen counts bytes up to NUL in O(n)
C++ std::string, std::string_view Bytes (UTF-8 by convention) string yes bytes
Java String (immutable), StringBuilder UTF-16 API; stored as Latin-1 or UTF-16 internally (compact strings, JDK 9+) No UTF-16 code units
Rust String (owned), &str (borrowed) Guaranteed valid UTF-8 String yes bytes; s[0] is a compile error
Zig []const u8 Bytes (UTF-8 by convention) via []u8 bytes
Go string (immutable), []byte Bytes (UTF-8 by convention) No bytes; range yields runes
let s = "héllo";
assert_eq!(s.len(), 6);                 // é is 2 bytes in UTF-8
assert_eq!(s.chars().count(), 5);       // code points
let first: Option<char> = s.chars().next();
// let c = s[1];                        // compile error: strings aren't indexable
let sub = &s[0..1];                     // OK: byte range on a char boundary
// &s[0..2] would PANIC: 2 is inside the 2-byte 'é'

Structs, records and memory layout

A struct (product type) groups named fields. Its size is not simply the sum of its fields, because of alignment: a CPU accesses a 4-byte int fastest, and on some architectures only, at an address divisible by 4. The compiler inserts padding to keep each field aligned.

C
struct Bad  { char a; int b; char c; };   // 1 + 3 pad + 4 + 1 + 3 pad = 12 bytes
struct Good { int b; char a; char c; };   // 4 + 1 + 1 + 2 pad = 8 bytes
Bad (12 B) a pad 3 b (int) c pad 3 Good (8 B) b (int) a c pad 2
Field order changes size. Each cell is one byte; hatched cells are padding.

Who controls layout?

  • C and C++ keep declaration order, so field order is part of the ABI. #pragma pack or __attribute__((packed)) removes padding at a speed cost.
  • Rust may reorder fields of a plain struct to minimise padding. #[repr(C)] forces C layout for FFI, and #[repr(packed)] packs it.
  • Zig also may reorder plain struct fields. extern struct gives C layout, and packed struct gives bit-exact layout, which is excellent for hardware registers and protocol headers (packed struct { flag: bool, kind: u3, len: u4 } is exactly one byte).
  • Go keeps declaration order and doesn't reorder. Linters like fieldalignment suggest better orders.
  • Java gives you no control. The JVM lays out object fields itself (grouping by size), and every object also has a 12–16 byte header (chapter 41). A class Point { int x, y; } takes about 16–24 bytes, not 8. That is why Project Valhalla's value classes matter: they allow flat, header-free arrays of small objects.

Records are immutable data carriers. Java record Point(int x, int y) auto-generates the constructor, accessors, equals, hashCode and toString. Rust gets similar behaviour with #[derive(Debug, Clone, PartialEq, Eq, Hash)], C++20 with = default comparisons, and Go structs are comparable with == by default.

Enums and sum types

A sum type (tagged union, variant, algebraic data type) holds one of several alternatives, each with its own data. A product type is "A and B." A sum type is "A or B." Together they're called algebraic data types, because the number of possible values multiplies or adds: struct {bool, bool} has 2×2 = 4 values, while enum {Bool(bool), Unit} has 2+1 = 3.

Sum types let you make illegal states unrepresentable. A connection that is either Connecting{attempt} or Connected{socket} or Failed{error} can't accidentally have a socket and an error.

Plain enum Sum type with data
C enum (just named ints) struct { enum Tag tag; union { … } u; } by hand, unchecked
C++ enum class (scoped, no implicit int) std::variant<A, B> + std::visit
Java enum (full classes, singletons, can have fields and methods) sealed interface + records (17+)
Rust enum enum with payloads, the core of the language (Option, Result)
Zig enum union(enum) tagged union
Go const + iota none; emulate with interfaces + type switch (not exhaustive)

Pointers, references and null

A pointer holds a memory address. A reference is a pointer with restrictions: it can't be null, can't be reseated, or has its lifetime checked. Null is the absence of a target. Tony Hoare, who introduced null references in 1965, later called them his "billion-dollar mistake," because every pointer becomes possibly-absent and the type system doesn't track which.

Nullable by default? How "maybe absent" is expressed Dereferencing null
C Yes NULL UB (usually SIGSEGV)
C++ Pointers yes, references no nullptr, std::optional<T> UB
Java Every reference null, Optional<T> (return values) NullPointerException (helpful messages since 14)
Rust No Option<T> (Some/None); Option<&T> is still one pointer wide Can't happen in safe code
Zig No ?T optional; ?*T is still one pointer wide .? unwrap panics in safe modes
Go Pointers, maps, slices, channels, interfaces, funcs nil panic (nil pointer dereference)

The null-pointer optimisation is why Option<&T> costs nothing: a reference can never be address 0, so the compiler uses 0 to mean None.

Modules, packages and visibility

Linkage, visibility and encapsulation boundaries

Large programs need boundaries: places where you decide what is public API and what is internal. Every language provides two levels: inside a file or module, and across packages.

  • C: static at file scope means internal linkage (invisible to other translation units). Everything else is global and shares one namespace, which is why C libraries prefix names (curl_easy_init, SDL_CreateWindow). The header is the public API by convention only.
  • C++: namespace for naming, anonymous namespaces for internal linkage, and public/private/protected for class members. C++20 modules add export.
  • Java: public, protected, package-private (no keyword), and private. Since Java 9, JPMS modules add a stronger layer: a module-info.java exports only chosen packages, so public classes in unexported packages are invisible outside the module.
  • Rust: everything is private by default. pub exports, and pub(crate) and pub(super) give finer control. Privacy is per module (a module sees its ancestors' private items). Crates are the unit of compilation and of publishing.
  • Zig: declarations are file-private unless marked pub. Struct fields are always public, by design. Zig trusts users and documents intent in naming instead.
  • Go: capitalisation is visibility. Exported vs unexported, at package level. An internal/ directory restricts importers to the parent tree.

Packages, dependencies and build tools

Package manager / build Manifest Lock file Registry
C/C++ None standard: CMake, Meson, Bazel; vcpkg and Conan for packages CMakeLists.txt, vcpkg.json varies none central
Java Maven, Gradle pom.xml, build.gradle.kts Gradle lockfiles Maven Central
Rust Cargo Cargo.toml Cargo.lock crates.io
Zig zig build (build script written in Zig) build.zig, build.zig.zon hashes in .zon URLs + content hashes, no central registry
Go go command, modules go.mod go.sum (checksums) proxy.golang.org + checksum DB

Go's minimal version selection picks the lowest version that satisfies every requirement, so builds are reproducible without a lock file solver. Cargo and npm pick the newest compatible versions and record them in a lock file. Zig and Go both identify dependencies by content hash, so a tampered tarball fails the build.

Abstraction, interfaces and polymorphism

Abstraction and abstract data types

Abstraction means hiding how behind what. An abstract data type (ADT) is defined by its operations and their laws, not by its representation. A stack is "push, pop, peek, with last-in-first-out order." Whether it's an array or a linked list is a hidden detail you can change later. The levels are:

  1. Procedural abstraction: name a computation (a function) so callers don't repeat the steps.
  2. Data abstraction: bundle data with the only operations allowed on it. In C this is an opaque pointer: the header says typedef struct Stack Stack; and Stack *stack_new(void);, and the struct's fields are defined only in the .c file. Callers can't touch the internals because they can't see them.
  3. Interface abstraction: many types share one set of operations, so code can work with any of them. This is polymorphism (from Greek, "many forms").

Kinds of polymorphism

  • Ad-hoc polymorphism: the same name with different implementations per type. Function overloading and operator overloading are examples.
  • Parametric polymorphism: code written once for any type (List<T>, Vec<T>). These are generics.
  • Subtype polymorphism: code written for a supertype works with any subtype (Animal a = new Dog()). This is inheritance and interfaces.
  • Bounded polymorphism: generics with constraints ("any T that can be compared"), such as Java <T extends Comparable<T>>, Rust T: Ord, C++20 std::totally_ordered T, and Go [T cmp.Ordered].

Interfaces and dynamic dispatch

How does shape.area() find the right code when the concrete type is only known at run time? Through a virtual method table (vtable): a per-type array of function pointers. Each object (or reference) carries a pointer to its type's vtable, and a call becomes "load vtable, load slot k, call indirectly."

C++ / Java: vptr inside the object vptr ● radius = 2.0 Circle object drop / dtor area → Circle::area draw → Circle::draw Circle vtable (one per type) Rust dyn Trait / Go interface: fat pointer data ptr ● vtable ptr ● &dyn Shape (2 words) radius = 2.0 plain data, no vptr size, align, drop area → Circle::area
Two vtable layouts. C++ and Java store the vtable pointer inside the object; Rust and Go put it in a fat pointer next to the data pointer.

The fat-pointer design means a Rust struct pays nothing for traits it could be used through. The vtable appears only where you actually write dyn Trait. In C++ and Java, any class with a virtual method carries a vptr in every instance.

How each language declares interfaces:

interface Shape {                      // nominal: you must write `implements`
    double area();
    default String describe() { return "area=" + area(); } // default method (Java 8+)
}
record Circle(double r) implements Shape { public double area() { return Math.PI * r * r; } }
record Square(double s) implements Shape { public double area() { return s * s; } }

double total(List<? extends Shape> shapes) {
    return shapes.stream().mapToDouble(Shape::area).sum(); // virtual call per element
}

Nominal vs structural. Java, C++, Rust and C# use nominal typing: a type implements an interface only if it declares it. Go uses structural typing for interfaces: having the methods is enough. This lets you define an interface in the consumer package that existing types already satisfy ("accept interfaces, return structs"), and keep interfaces tiny (io.Reader has one method). The cost is accidental satisfaction and a less discoverable "who implements this?"

Rust's orphan rule says you may implement a trait for a type only if your crate owns the trait or the type. This prevents two crates from supplying conflicting implementations.

Static versus dynamic dispatch

Static dispatch means the call target is known at compile time. It can be inlined, which enables most other optimisations. Dynamic dispatch means the call goes through a vtable or function pointer: one or two extra loads plus an indirect branch. That's usually just a few nanoseconds, but it blocks inlining and can mispredict. Hot inner loops prefer static dispatch. Plugin systems and heterogeneous collections need dynamic dispatch.

Java blurs the line. The JIT watches call sites, and if a "virtual" call only ever sees one receiver type (monomorphic), it inlines it with a cheap type-check guard. If a new class loads later, it deoptimises. This is why idiomatic Java with interfaces everywhere is still fast.

Generics: three implementation strategies

The languages implement "write once, use for any T" in three fundamentally different ways:

Strategy Languages How it works Pros Cons
Monomorphisation C++ templates, Rust, Zig comptime Compile a separate copy for each concrete type Fastest: everything inlines, no boxing Bigger binaries, slower builds
Type erasure Java Check types at compile time, then erase T to Object (or its bound); one copy of the code Small code, binary compatible with pre-generics Java Boxing of primitives, no new T(), no T.class, no List<int>, unchecked casts
Dictionary / GC-shape stenciling Go One copy per shape (all pointer types share one copy), plus a hidden dictionary argument with type info Balance of code size and speed Method calls on type parameters can be slower than hand-written code
// Erasure in practice
List<String> a = new ArrayList<>();
List<Integer> b = new ArrayList<>();
System.out.println(a.getClass() == b.getClass());  // true: both are just ArrayList at run time
// static <T> T make() { return new T(); }          // compile error: T is erased
static <T> T make(Supplier<T> f) { return f.get(); } // pass a factory instead
List<Integer> nums = List.of(1, 2, 3);               // each Integer is a boxed heap object

Variance asks: if Cat is a subtype of Animal, is List<Cat> a subtype of List<Animal>? For a mutable list, no. Otherwise you could add a Dog through the List<Animal> view. Java arrays got this wrong (Animal[] a = new Cat[1]; a[0] = new Dog(); compiles and throws ArrayStoreException at run time). Java generics are invariant and use wildcards (? extends, ? super) for read-only and write-only views. Chapter 36 of the roadmap covers this as PECS. Rust infers variance automatically for lifetimes and type parameters.

Error handling

The error models

Every program meets failure: missing files, bad input, full disks, network timeouts, bugs. There are two different kinds:

  • Recoverable errors: expected conditions the caller should handle, such as "file not found" or "invalid input."
  • Unrecoverable errors (bugs): violated invariants, such as an index out of range or unreachable reached. The right response is usually to stop.

Languages offer these mechanisms:

Model Languages Visible in the signature? Can it be ignored silently?
Return codes + errno C No (convention only) Yes, very easily
Exceptions (unchecked) C++, Java RuntimeException No (noexcept marks the opposite) Yes: they propagate invisibly
Checked exceptions Java Yes (throws IOException) No: you must catch or declare
Error values Go ((T, error)) Yes Possible (_), linters catch it
Result types Rust Result<T, E>, C++23 std::expected Yes No: #[must_use] warns, and you must unwrap to get T
Error unions Zig !T Yes, including the precise error set No: compile error to ignore
Panic / abort Rust panic!, Go panic, Zig @panic, C abort — For bugs, not for control flow

The same task in every model

Read a config file and parse a port number. Two things can fail: I/O and parsing.

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

// returns 0 on success, -1 on failure (errno set); result via out-param
int read_port(const char *path, int *out) {
    FILE *f = fopen(path, "r");
    if (!f) return -1;                       // errno = ENOENT etc. set by fopen
    char buf[32];
    if (!fgets(buf, sizeof buf, f)) { fclose(f); errno = EIO; return -1; }
    fclose(f);
    char *end;
    errno = 0;
    long v = strtol(buf, &end, 10);
    if (errno || end == buf || v < 1 || v > 65535) { errno = EINVAL; return -1; }
    *out = (int)v;
    return 0;
}
// caller: if (read_port("p.conf", &port) != 0) perror("read_port");

Designing errors well

Whatever the mechanism, the same rules apply:

  1. Add context as errors travel up. "No such file" is useless. "Loading config /etc/app.conf: no such file" is actionable. Go uses fmt.Errorf("…: %w", err), Rust uses anyhow's .context(…), Java uses exception chaining (new X(msg, cause)), and Zig has error return traces built in, which show every try the error passed through.
  2. Let callers distinguish errors they can act on. Use specific types, codes or sentinels (os.ErrNotExist, io::ErrorKind::NotFound, error.FileNotFound), not just strings.
  3. Don't use errors for control flow on hot paths. Exceptions are cheap when nothing is thrown, but throwing captures a stack trace, which is expensive in Java.
  4. Fail fast on bugs. Assertions, panic, unreachable and Objects.requireNonNull stop the program close to the cause.
  5. Never swallow errors. An empty catch {}, _ = err, or .unwrap() in a library are all ways errors disappear.

State, immutability, values and ownership

State and side effects

State is data that changes over time. A side effect is anything a function does besides computing its return value: mutating a variable outside itself, I/O, throwing, reading the clock. A pure function has no side effects and returns the same output for the same input. That makes it trivially testable, cacheable (memoisation), parallelisable and reorderable.

Real programs need effects. The craft is to push them to the edges: keep a pure core that computes decisions and a thin imperative shell that performs I/O. People call this "functional core, imperative shell."

Immutability

Immutability comes in grades:

  1. Immutable binding: the variable can't be reassigned (final, let, const in Zig).
  2. Shallow immutability: the object's fields can't be reassigned, but objects they reference can change. A Java record holding a List is like this.
  3. Deep immutability: nothing reachable can change. Java String, Go string, Rust &T (with no interior mutability), and persistent data structures all work this way.
Default Immutable view Notes
C Mutable const T * const can be cast away. Modifying a truly const object is UB
C++ Mutable const T&, const methods mutable fields can change inside const methods
Java Mutable final fields, List.copyOf, records No deep-const in the type system
Rust Immutable &T &mut T is required to mutate. Interior mutability (Cell, RefCell, Mutex) is opt-in and visible in types
Zig const preferred (the compiler errors on a never-mutated var) *const T, []const T
Go Mutable none (except strings) Pass copies or unexported fields with getters

Value semantics versus reference semantics

This is the deepest conceptual split between languages.

  • Value semantics: assignment copies. b = a; b.x = 5; leaves a unchanged. Each variable owns independent data. C structs, C++ objects, Go structs and arrays, Rust (where a "copy" is a move for non-Copy types), Zig, and Java primitives all behave this way.
  • Reference semantics: assignment shares. b = a; b.x = 5; changes what a sees, because both name the same object. Java objects (all of them), Python, JavaScript objects, and Go slices, maps, channels and pointers all behave this way.
type P struct{ X int }
a := P{1}
b := a          // copy of the struct
b.X = 5         // a.X is still 1

arr := [3]int{1, 2, 3}
arr2 := arr     // arrays are values: full copy
arr2[0] = 9     // arr[0] still 1

s := []int{1, 2, 3}
s2 := s         // slices are headers: shared backing array
s2[0] = 9       // s[0] is now 9!

Ownership and memory management models

Who frees memory, and when? This decides a language's safety and performance more than anything else.

Model Languages Who frees Typical failure
Manual C, Zig You (free, allocator.free) Leaks, use-after-free, double free
Scope-bound (RAII) C++, Rust Destructor at end of scope (C++) dangling references to destroyed objects
Tracing GC Java, Go, C#, JS A collector finds unreachable objects Pauses, memory overhead, non-memory resources still need closing
Reference counting Swift (ARC), Python, C++ shared_ptr, Rust Rc/Arc Freed when the count hits 0 Cycles leak; atomic counts cost time
Ownership + borrowing (compile-time) Rust Compiler inserts drops; borrow checker proves no dangling Steeper learning curve; some patterns (graphs) need Rc/indices

Rust's rules, which you should memorise:

  1. Every value has exactly one owner.
  2. When the owner goes out of scope, the value is dropped.
  3. You may have either any number of shared borrows &T or exactly one mutable borrow &mut T. Never both at once. This is "aliasing XOR mutability."
  4. A borrow can't outlive what it borrows. Lifetimes ('a) name these regions, and the compiler checks them.

Rule 3 alone eliminates data races and iterator invalidation at compile time. C++ gets close with std::unique_ptr (single owner, move-only) and std::shared_ptr (refcounted), but it can't stop you keeping a raw reference after the owner dies.

Zig's model is manual, but explicit about allocation. Any function that allocates takes an Allocator parameter, so you can see from a signature whether it allocates, and you can hand it an arena, a fixed buffer, or a leak-detecting test allocator. std.testing.allocator fails your test if you leak.

fn longest<'a>(a: &'a str, b: &'a str) -> &'a str { if a.len() > b.len() { a } else { b } }

let r;
{
    let s = String::from("inner");
    // r = &s;            // error: `s` does not live long enough
}
let mut v = vec![1, 2, 3];
let first = &v[0];
// v.push(4);            // error: cannot borrow `v` as mutable while `first` is alive
println!("{first}");

Aliasing and mutation hazards

Aliasing means two names refer to the same memory. Aliasing alone is harmless, and so is mutation alone. Aliasing plus mutation causes most memory and concurrency bugs:

  • Iterator invalidation: you mutate a container while holding a reference into it.
  • Data races: two threads access the same memory, at least one writes, with no synchronisation (chapter 8).
  • Spooky action at a distance: a function modifies a list you passed it, and your caller's copy changes too.
  • Missed optimisations: in C, the compiler must assume two pointers might alias, so it reloads values. restrict promises they don't. Rust's &mut gives that promise automatically.

Each language's defence: C and C++ rely on discipline and sanitizers. Java relies on immutability conventions and defensive copies. Go relies on "don't communicate by sharing memory; share memory by communicating" plus the race detector (go test -race). Rust makes it a compile error. Zig relies on discipline and safety checks.

Input/output and serialization

Streams, buffering and files

Programs talk to the outside world through the OS (chapter 8): file descriptors and system calls like read(fd, buf, n) and write. Each system call costs roughly 100 ns to a few µs, so writing one byte at a time is very slow. Buffering collects small writes into a block (often 4–64 KB) and makes one system call per block.

Each language layers abstractions over raw file descriptors:

  • C: FILE* with fopen/fread/fprintf. stdout is line-buffered on a terminal and fully buffered when piped. That's why printf output seems to "disappear" when a program crashes while piped: the buffer was never flushed.
  • C++: iostream (std::cout, std::ifstream). It is synchronised with C stdio by default, which is slow; std::ios::sync_with_stdio(false) disables that. C++23 adds std::print.
  • Java: byte streams (InputStream/OutputStream), char readers and writers that decode text, BufferedReader, Files.readAllLines, and NIO channels and buffers.
  • Rust: std::io::Read/Write traits, BufReader/BufWriter. stdout is line-buffered, and println! locks stdout on each call, so lock it once for bulk output.
  • Go: the io.Reader/io.Writer interfaces (one method each) compose everything: files, network connections, compressors, hashes. Use bufio for buffering.
  • Zig: since 0.15, the std.Io.Reader/std.Io.Writer interfaces put the buffer in the interface, and you must call flush(). std.debug.print writes unbuffered to stderr and is handy for learning.
// Count lines in a file: buffered, streaming, constant memory
f, err := os.Open("big.log")
if err != nil { log.Fatal(err) }
defer f.Close()
sc := bufio.NewScanner(f)
n := 0
for sc.Scan() { n++ }
if err := sc.Err(); err != nil { log.Fatal(err) }
fmt.Println(n)

Text, binary and encodings

A file is just bytes. "Text" is bytes plus an agreed encoding. Today that is almost always UTF-8 (chapter 6). Two traps catch people:

  • Line endings: \n on Unix and \r\n on Windows. C's text mode on Windows translates them, and binary mode ("rb") doesn't.
  • Platform default charsets: Java used the OS default charset until JDK 18 made UTF-8 the default (JEP 400). Always pass a charset explicitly in older code.

Serialization and schema evolution

Serialization turns in-memory structures (with pointers, padding and native byte order) into a self-contained byte sequence for storage or the network. Deserialization reverses it. The main formats:

Format Kind Schema? Strengths Weaknesses
JSON Text Optional (JSON Schema) Universal, readable Verbose, no binary data, numbers are ambiguous (precision beyond 2⁵³)
CSV Text No Spreadsheets Quoting chaos
Protocol Buffers Binary Required (.proto) Compact, fast, field numbers enable evolution Not human-readable
Avro Binary Required (sent or registered) Kafka ecosystems, schema registry Needs the writer's schema to read
MessagePack / CBOR Binary No Binary JSON Less tooling
FlatBuffers / Cap'n Proto Binary Required Zero-copy: read fields in place without parsing Awkward to build

Language support: Rust serde (derive Serialize/Deserialize, one model for every format), Go encoding/json with struct tags (json:"name,omitempty"), Java Jackson or Gson (and records work well), C++ nlohmann/json or simdjson, Zig std.json, and C cJSON.

Schema evolution means old and new versions of a program must read each other's data:

  • Backward compatible: new code reads old data. Added fields need defaults.
  • Forward compatible: old code reads new data. It must ignore unknown fields.
  • Never reuse a field number or tag (protobuf), and never change a field's type in place.

Endianness is the byte order of multi-byte numbers in memory. x86 and most ARM systems are little-endian (least significant byte first). Network protocols are big-endian ("network byte order"). Binary formats must pick one and convert: C htonl, Go binary.BigEndian.PutUint32, Rust u32::to_be_bytes, Zig std.mem.writeInt(u32, buf, v, .big), Java ByteBuffer.order(...). Chapter 6 covers this in depth.

Testing and debugging

Testing fundamentals and built-in tooling

A test is a program that checks another program. The basic shape is arrange, act, assert. Good unit tests are fast, isolated, repeatable and self-validating, and they test behaviour (what) rather than implementation (how), so refactoring doesn't break them. Part XI of the roadmap goes deep. Here is how each language runs tests:

pub fn add(a: i32, b: i32) -> i32 { a + b }

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn adds() { assert_eq!(add(2, 3), 5); }
    #[test]
    #[should_panic]
    fn overflow_panics_in_debug() { add(i32::MAX, 1); }
}
// run: cargo test   (doc-comment examples are tests too)

Rust, Go and Zig build testing into the toolchain, which is one reason their ecosystems test more consistently. Go also builds in benchmarks and fuzzing. Rust has cargo bench (nightly) and the criterion crate, plus cargo fuzz.

Debugging tools and techniques

Debugging is the scientific method applied to code: observe the symptom, hypothesise a cause, predict what you'd see if the hypothesis were true, test it, and narrow down. Tools, from cheapest to most powerful:

  1. Read the error. Stack traces, panic messages, compiler errors. Rust's and Zig's compiler errors in particular often contain the fix.
  2. Print debugging / logging. It's underrated, and the only option in production. Use structured logs (chapter 99).
  3. Assertions: assert, debug_assert!, std.debug.assert, Java assert (disabled unless you pass -ea).
  4. Debuggers: gdb and lldb for C, C++, Rust and Zig; Delve (dlv) for Go, which understands goroutines; IDE and JDWP debuggers for Java, which can attach to a running JVM. Core skills are breakpoints, conditional breakpoints, watchpoints (break when memory changes), stepping, backtraces, and inspecting frames.
  5. Sanitizers (C, C++, Rust nightly, Zig): compile with -fsanitize=address (out-of-bounds, use-after-free), =undefined (UB checks), =thread (data races), or =memory. They're about 2× slower and find bugs that otherwise show up months later. Valgrind finds similar bugs without recompiling.
  6. Race detectors: go test -race, TSan.
  7. Core dumps and post-mortems: inspect the crash state after the fact. Java has heap dumps (jmap) and thread dumps (jstack).
  8. git bisect: binary-search history for the commit that introduced a bug, in O(log n) steps.
  9. Record and replay (rr on Linux): record once, then step backwards through execution.

Undefined behaviour

Undefined behaviour (UB) is any operation the C or C++ standard says nothing about. Examples: signed overflow, out-of-bounds access, use-after-free, data races, null dereference, reading uninitialised memory, violating strict aliasing. The compiler assumes UB never happens and optimises on that basis. The resulting program can do anything, including working fine until a compiler upgrade.

C
int table[4];
bool exists_in_table(int v) {
    for (int i = 0; i <= 4; i++)        // bug: reads table[4]
        if (table[i] == v) return true;
    return false;
}
// Optimising compilers have turned this into `return true;`: since reading table[4] is UB,
// the compiler may assume the loop always exits via `return true` before i reaches 4.

How the others handle it:

  • Java and Go define (nearly) everything. Out-of-bounds throws or panics. Data races in Go can still corrupt multi-word values such as interfaces and slices.
  • Rust has no UB in safe code. unsafe blocks can cause it, and you must uphold the invariants there. The Miri interpreter detects UB in tests.
  • Zig has "illegal behaviour." In Debug and ReleaseSafe builds most of it is checked and panics with a stack trace. In ReleaseFast it is UB, as in C. You choose per build, or per block with @setRuntimeSafety.

Programming paradigms

A paradigm is a style of structuring computation: a set of ideas about what a program is. Languages support paradigms; they don't own them. You can write object-oriented C (the Linux kernel's file_operations is a vtable) and functional Java. Knowing the paradigms lets you pick the right shape for each problem.

programming imperative: HOW declarative: WHAT procedural object-oriented functional logic query / dataflow cross-cutting: generic concurrent data-oriented metaprogramming
A family tree of paradigms. Most modern languages are multi-paradigm and sit across several branches.

Imperative and procedural programming

Imperative programming describes computation as a sequence of commands that change state: assign, loop, branch. It mirrors the hardware, which is a CPU mutating registers and memory step by step. Procedural programming organises imperative code into procedures (functions) that operate on data passed to them. Structured programming (Dijkstra, 1968: "Go To Statement Considered Harmful") restricts control flow to sequence, selection and iteration, so each block has one entry and one exit and can be read locally.

C is the archetype, and Go and Zig are deliberately procedural-first. The strengths are direct mapping to the machine, predictable performance, and easy reading of "what happens next." The weakness is that state is spread across the program, and as it grows, knowing who changes what becomes the hard problem.

Object-oriented programming

OOP organises programs around objects: bundles of state plus the behaviour that operates on it, which talk to each other through messages (method calls). The four classic pillars are encapsulation (hide state behind methods), abstraction, inheritance (derive classes from classes) and polymorphism. Chapter 34 of the roadmap covers OOP design in depth.

There are two lineages:

  • Simula/C++ style (class-based, static): Java, C#, C++. Objects are instances of classes, and methods are resolved through vtables.
  • Smalltalk style (message passing, dynamic): Ruby, Objective-C, and the idea behind Erlang's actors. "Calling a method" means sending a message the receiver interprets at run time. Alan Kay, who coined "object-oriented," said messaging was the main idea, not classes.
  • Prototype-based: JavaScript and Lua. There are no classes underneath; objects delegate to other objects.

How the six languages relate to OOP:

Classes Inheritance Interfaces Notes
C No No Function-pointer structs OOP by convention (GObject, kernel)
C++ Yes Multiple, including virtual inheritance Abstract classes, concepts Everything optional and zero-cost if unused
Java Yes (everything lives in one) Single class, multiple interfaces Yes The canonical class-based OOP language
Rust No (structs + impl) No implementation inheritance Traits Composition and traits only
Zig No (structs with methods) No No (by convention) Methods are namespaced functions
Go No (structs + methods) No; embedding promotes fields and methods Structural interfaces "Composition over inheritance" built in

Rust and Go deliberately dropped implementation inheritance. The industry's experience with deep class hierarchies (the fragile base class problem, where changing a parent silently breaks children, plus tight coupling and the banana-gorilla-jungle problem) led to the advice favour composition over inheritance (Gang of Four, 1994). Both languages enforce that advice.

Functional programming

Functional programming (FP) treats computation as evaluating functions in the mathematical sense: outputs depend only on inputs, and nothing is mutated. Its core ideas:

  • Pure functions and referential transparency: an expression can be replaced by its value without changing the program.
  • Immutable data: you create new values instead of changing old ones. Persistent data structures make this efficient through structural sharing.
  • First-class and higher-order functions: map, filter, fold, function composition.
  • Algebraic data types and pattern matching: model data as sums and products, and handle every case.
  • Recursion instead of loops, with guaranteed tail calls in FP languages.
  • Laziness (Haskell): evaluate only when needed, which allows infinite lists.
  • Effects as values: describe side effects (I/O, state, errors) as data that a runtime executes. Haskell's IO monad, and the Option/Result chaining in Rust, are examples of this idea.
-- Pure, lazy, everything is an expression
data Shape = Circle Double | Rect Double Double

area :: Shape -> Double
area (Circle r) = pi * r * r
area (Rect w h) = w * h

totalArea :: [Shape] -> Double
totalArea = sum . map area            -- function composition, point-free

primes = sieve [2..] where sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0]
-- take 5 primes == [2,3,5,7,11]   (infinite list, evaluated lazily)

Why FP matters to a backend engineer even if you never write Haskell: pure functions are easy to test, parallelise and cache. Immutable messages make concurrency safe. Event sourcing is a fold over events. React's UI = f(state) is FP. Stream processing (Kafka Streams, Java Streams) is map/filter/reduce at scale.

Declarative and logic programming

Declarative programming states what result you want and leaves how to the system. The best-known example is SQL: you describe the rows you want, and the query planner (chapter 60) chooses indexes, join order and algorithms. Others include HTML and CSS, regular expressions, build files (Bazel, Nix), Terraform and Kubernetes manifests (desired state that a controller reconciles), and spreadsheet formulas.

Logic programming (Prolog, Datalog) declares facts and rules, then asks queries. The engine searches for answers by unification (pattern matching both ways) and backtracking.

parent(tom, bob).
parent(bob, ann).
parent(bob, pat).

grandparent(X, Z) :- parent(X, Y), parent(Y, Z).   % rule

% ?- grandparent(tom, Who).
% Who = ann ;
% Who = pat.

Datalog is a restricted Prolog that always terminates. It powers static analysers (CodeQL, Soufflé), authorisation engines (Google Zanzibar-style systems, Open Policy Agent's Rego is similar) and some databases.

Generic programming and metaprogramming

Generic programming writes algorithms once in terms of the operations they need. Stepanov's C++ STL is the landmark: std::sort works on any random-access iterator with any comparator, with no runtime cost. The section on generics earlier in this chapter covers the implementation strategies.

Metaprogramming is code that writes or inspects code:

Technique When Languages
Text macros Before parsing C/C++ preprocessor (#define, token pasting)
Template metaprogramming Compile time C++ (Turing-complete by accident; constexpr made it sane)
Hygienic / syntactic macros Compile time, on token trees Rust macro_rules! and procedural macros (#[derive(Serialize)]), Lisp
Compile-time execution Compile time, ordinary code Zig comptime, C++ consteval, Rust const fn (limited)
Code generation Build step Go go generate, protobuf compilers, Java annotation processors (Lombok, MapStruct)
Reflection Run time Java (Class, Method, used heavily by Spring), Go reflect (used by encoding/json), C++26 adds static reflection
Bytecode manipulation Load/run time Java agents, ByteBuddy, ASM (how Spring proxies, Mockito and Hibernate work)

Zig's approach is the most unusual. There is no macro language and no template language, only Zig code that runs at compile time. Generic data structures are just functions that return a type, and std.debug.print's format string is parsed and type-checked at compile time by ordinary Zig code.

Concurrent programming models

Concurrency means structuring a program as independently progressing tasks. Parallelism means actually running at the same time on multiple cores. Chapter 8 covers the OS mechanics, and chapter 38 covers Java's toolkit. The paradigm-level models are:

Model Idea Where you see it
Threads + shared memory + locks Many threads, one address space, protect shared data with mutexes C (pthreads), C++ std::thread, Java, Rust (with compile-time race freedom), Zig std.Thread
CSP (Communicating Sequential Processes, Hoare 1978) Independent processes communicate over channels; share memory by communicating Go goroutines + channels, Rust mpsc/crossbeam, Clojure core.async
Actors (Hewitt 1973) Each actor has private state and a mailbox; it reacts to messages one at a time; failures are supervised Erlang/Elixir, Akka (JVM), Orleans
async/await (futures) Functions suspend at await without blocking a thread; an event loop or executor resumes them Rust (tokio), C# , JS, Python, C++20 coroutines, Kotlin
Virtual / green threads Cheap user-space threads scheduled by the runtime onto OS threads (M:N); you write blocking-style code Go goroutines, Java virtual threads (21+), Erlang processes
Data parallelism Apply one operation to many elements at once SIMD, GPU (CUDA), Java parallel streams, Rust rayon, OpenMP
Software transactional memory Group memory operations into atomic transactions that retry on conflict Clojure, Haskell
// CSP: a pipeline of goroutines connected by channels
func gen(nums ...int) <-chan int {
	out := make(chan int)
	go func() { for _, n := range nums { out <- n }; close(out) }()
	return out
}
func square(in <-chan int) <-chan int {
	out := make(chan int)
	go func() { for n := range in { out <- n * n }; close(out) }()
	return out
}
func main() {
	for v := range square(gen(1, 2, 3)) { fmt.Println(v) } // 1 4 9
}

Data-oriented design

Data-oriented design (DOD) starts from how data flows through the hardware, the cache in particular (chapter 7), rather than from how concepts relate. Its signature move is changing an array of structs (AoS) into a struct of arrays (SoA).

Text
AoS: [ {x,y,z,alive,name…}, {x,y,z,alive,name…}, … ]   update positions → drags names through cache
SoA: xs: [x,x,x,…]  ys: [y,y,y,…]  alive: [1,0,1,…]       update positions → touches only xs, ys: dense, SIMD-friendly

When a loop touches two fields of a 64-byte object, AoS wastes most of every 64-byte cache line it loads. SoA uses every byte it loads. Game engines (entity-component systems), columnar databases (DuckDB, Parquet, ClickHouse), and the Zig compiler itself use this approach. The Zig standard library's std.MultiArrayList converts an AoS type into SoA storage automatically. Java's object-per-element model makes DOD hard, which is part of the motivation for Project Valhalla.

Multi-paradigm languages and choosing a style

All six languages are multi-paradigm in practice:

  • C: procedural, with OOP by convention.
  • C++: procedural, OOP, generic, functional (lambdas, ranges), metaprogramming. It has everything, so teams must choose a subset.
  • Java: OOP first, with functional features since Java 8 and data-oriented features since 16–21 (records, sealed types, patterns).
  • Rust: functional-flavoured (ADTs, iterators, expressions), plus traits for polymorphism and imperative code where it fits.
  • Zig: procedural plus comptime metaprogramming, with data orientation encouraged.
  • Go: procedural plus structural interfaces plus CSP.

A practical guide: model data with sum and product types; write logic as pure functions over that data; isolate effects at the edges; use objects or interfaces where you need swappable implementations; choose a concurrency model to match the workload (CSP or virtual threads for I/O-bound services, data parallelism for CPU-bound batch work).

Type systems

Static, dynamic, strong and weak typing

Two independent axes are often confused:

  • Static vs dynamic is when types are checked. Static means at compile time (all six languages, plus TypeScript). Dynamic means at run time (Python, JavaScript, Ruby). Static checking catches whole classes of bugs before the program runs and enables better tooling and optimisation. Dynamic checking is more flexible and quicker to prototype with. Gradual typing (TypeScript, Python type hints) mixes the two.
  • Strong vs weak is how much the language converts implicitly or lets you reinterpret bits. These are informal terms. C is statically typed but fairly weak: implicit conversions, void*, unions and casts let you treat any bytes as any type. JavaScript is dynamic and weak ("5" * 2 === 10). Python is dynamic and strong ("5" * 2 == "55", and "5" + 2 raises TypeError). Rust and Go are static and strong.

Type soundness means that if the program type-checks, no run-time type error can occur in the parts the type system covers. Java is sound except for documented holes (array covariance throws ArrayStoreException, and unchecked generic casts). Safe Rust aims for soundness. C is not sound at all.

Nominal versus structural typing

  • Nominal: types are compatible only if they have the same name, or a declared subtyping relationship. Java, C#, C++ classes, Rust, and Go named types all work this way: type Celsius float64 and type Fahrenheit float64 are distinct, so you can't add them by accident.
  • Structural: types are compatible if they have the same shape. Go interfaces, TypeScript, and OCaml objects work this way.

Nominal typing gives you newtypes: wrapping a primitive to stop mix-ups (UserId(u64) vs OrderId(u64)). It costs nothing at run time and prevents a whole class of bugs. The NASA Mars Climate Orbiter was lost in 1999 to a pound-seconds versus newton-seconds mix-up that unit types would have caught.

Type inference

Type inference means the compiler works out types you didn't write. There are two levels:

  • Local inference: types flow forward from initialisers (var x = new ArrayList<String>(), auto, x := 5). Java, C++ and Go do this.
  • Bidirectional / Hindley–Milner-style inference: types also flow backward from later use. In Rust, let mut v = Vec::new(); v.push(1u8); makes v a Vec<u8> because of the later push. Haskell and OCaml infer whole programs. Rust deliberately requires types on function signatures, so inference stays local to a function body and signatures stay readable contracts.

Null safety, option types and the type of "nothing"

You saw Option<T> and ?T earlier. The general principle is to make absence part of the type, so the compiler forces you to handle it. Related types worth knowing:

  • Unit (() in Rust, void in C/C++/Java, void in Zig, nothing in Go): exactly one value, meaning "no interesting result."
  • Never / bottom (! in Rust and Zig's noreturn, Java has none, C has _Noreturn/[[noreturn]]): no values. It's the type of panic!(), loop {} and exit(). Because it has no values, it can stand in for any type, which is why let x: i32 = if c { 5 } else { panic!() }; type-checks.
  • Top / any (Object in Java, any in Go and TypeScript, void* in C, anyopaque in Zig): every value fits, and you need a check or cast to get anything back.

The six languages side by side

Summary comparison

C C++ Java Rust Zig Go
First appeared 1972 1985 1995 2015 (1.0) 2016 (pre-1.0) 2012 (1.0)
Execution Native AOT Native AOT Bytecode + JIT (AOT via GraalVM) Native AOT (LLVM) Native AOT (LLVM + own backends) Native AOT (own compiler)
Memory Manual RAII + smart pointers Tracing GC Ownership + borrowing Manual, explicit allocators Tracing GC (concurrent)
Null Yes Pointers All references No (Option) No (?T) Yes (nil)
Errors Codes, errno Exceptions, expected Exceptions (checked + unchecked) Result, panic Error unions, try error values, panic
Generics Macros, _Generic Templates, concepts Erasure Monomorphisation + traits comptime Stenciling + constraints
Polymorphism Function pointers Virtual + templates Interfaces, virtual by default Traits (static or dyn) Duck typing, manual vtables Structural interfaces
Concurrency pthreads std::thread, atomics, coroutines Threads, virtual threads, java.util.concurrent Threads, async, compile-time race freedom Threads, atomics Goroutines, channels
UB in normal code Common Common None None in safe code Checked in safe builds Rare (data races)
Sweet spot OS, embedded, ABI glue Games, browsers, HFT, engines Enterprise backends, Android Systems + safety, infra, CLIs Low-level control, C interop, toolchains Cloud services, CLIs, DevOps tools

How to study the languages together

  1. Learn concepts once, map them six times. For each section of this chapter, ask "where does this live in each language?" The tables are your map.
  2. Write the same small program in each. Good candidates: a word-frequency counter (strings, maps, I/O, errors), a linked list (pointers and ownership), and a thread pool (concurrency).
  3. Read compiler output. Paste code into Compiler Explorer (godbolt.org), compare C, Rust, Zig and Go side by side, and look at the assembly. Chapter 7 will make that readable.
  4. Notice the trade-offs, not the winners. Every row of the summary table is a trade-off someone made on purpose.

Lab: programming fundamentals, measured

The sections above explain the ideas. This lab makes them visible. Every program here was compiled and run (GCC 13, JDK 21, Go 1.24, Rust 1.97, Zig 0.17, CPython 3.13, Node 22) and the output shown is the real output. Run them yourself, change them, and predict the result before you look: that's how L2 becomes L3.

From source to running process, stage by stage

The roadmap's first nuance is the pipeline source → compiler/interpreter → executable/runtime representation → CPU/VM execution. Here it is for one tiny C program, stopping after each stage:

C
// square.c
#include <stdio.h>
#define FACTOR 3
static int square(int x) { return x * x; }
int main(void) { printf("%d\n", square(7) * FACTOR); return 0; }
Terminal
$ gcc -E square.c | wc -l          # 1. preprocess: #include pastes in stdio.h, #define is substituted
817
$ gcc -E square.c | tail -2
static int square(int x) { return x * x; }
int main(void) { printf("%d\n", square(7) * 3); return 0; }

$ gcc -O2 -S -o - square.c         # 2. compile to assembly
main:
        endbr64
        subq    $8, %rsp
        movl    $147, %edx           # square(7) * 3 computed at compile time: the function is gone

$ gcc -O2 -c square.c && nm square.o   # 3. assemble into a relocatable object
                 U __printf_chk      # U = undefined: to be resolved by the linker
0000000000000000 T main

$ gcc -O2 -o square square.o && ldd square   # 4. link into an executable that loads libc at run time
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
        /lib64/ld-linux-x86-64.so.2          # the dynamic loader (chapter 10)
$ ./square                                    # 5. the kernel loads it; the CPU executes it
147

Three lessons hide in that output. Your 4-line file became 817 lines before the compiler proper saw it (headers are textual inclusion in C and C++; modules in other languages avoid this). The optimiser removed square entirely and printed a constant: what runs is not a line-by-line translation of what you wrote, which is why you debug at -O0 and benchmark at -O2. And the object file still had an undefined symbol that only the linker resolves, which is where "undefined reference" errors come from.

The same function in managed and interpreted runtimes stops at a different representation:

Terminal
$ javap -c Square        # Java: bytecode for a stack machine, JIT-compiled later (chapter 10)
  static int square(int);
    Code:
       0: iload_0
       1: iload_0
       2: imul
       3: ireturn

$ python3 -c "import dis; dis.dis(lambda x: x * x)"   # CPython 3.13: bytecode run by the interpreter loop
  RESUME                   0
  LOAD_FAST_LOAD_FAST      0 (x, x)
  BINARY_OP                5 (*)
  RETURN_VALUE

And the artefact you ship differs enormously by language, for the same "print 147" program on Linux x86-64:

Build Size Why
C, dynamically linked (gcc -O2) 15,968 bytes libc is shared, loaded at run time
C, stripped 14,472 bytes symbol table removed
C, statically linked (-static) 785,328 bytes libc copied in
Zig, -O ReleaseSmall 135,712 bytes static, minimal std
Rust -O, stripped 342,552 bytes static Rust std, dynamic libc
Rust -O, unstripped 4,358,760 bytes debug info for std
Go, stripped (-ldflags="-s -w") 1,433,784 bytes static, includes the Go runtime (scheduler, GC)
Go, default 2,209,231 bytes plus symbol tables
Java 1 KB .class + a ~200 MB JDK the runtime is installed separately

None of these is "better": a Go binary carries its scheduler and garbage collector and needs nothing installed; a C binary depends on the system's libc version; a Java class needs a JVM. That trade-off returns in containers (Volume 6) and in startup time (chapter 10).

Value, reference and ownership semantics, side by side

The roadmap's second nuance: value semantics vs reference semantics vs ownership semantics. The question each answers is: after b = a, then changing b, does a change?

value (C struct, Go array, Rust Copy types) a: {1,2} b: {99,2} two independent copies reference (Java objects, Python, C pointers, Go slices) xs ys [99, 2, 3] aliasing ownership (Rust, C++ moves) v ✗ consume(v) moved exactly one owner at a time; use after move is a compile error
Three answers to "what does b = a mean?". With value semantics the data is copied and the two variables are independent. With reference semantics both names point at one object, so a change through either is visible through both. With ownership semantics the data moves: a becomes unusable, so there is never more than one owner and no aliasing to reason about.

Five programs, one per behaviour:

C
// C: structs copy by value, but a struct containing a pointer copies only the pointer
typedef struct { int x, y; } Point;
typedef struct { int *data; int len; } View;
Point a = {1, 2}; Point b = a; b.x = 99;              // independent copy
int buf[3] = {1, 2, 3};
View v = {buf, 3}; View w = v; w.data[0] = 99;        // shallow copy: v and w share buf
Java
// Java: primitives copy; objects are reached through references; boxed values have identity
int a = 1; int b = a; b = 99;
List<Integer> xs = new ArrayList<>(List.of(1, 2, 3));
List<Integer> ys = xs; ys.set(0, 99);
Integer i1 = 127, i2 = 127, i3 = 128, i4 = 128;
System.out.println((i1 == i2) + " " + (i3 == i4) + " " + i3.equals(i4));
Go
// Go: arrays are values; slices are small headers {pointer, len, cap} over a shared backing array
a := [3]int{1, 2, 3}
b := a // full copy
b[0] = 99
s := make([]int, 3, 4) // len 3, capacity 4
t := append(s, 4)      // fits in capacity: writes into s's backing array
u := append(s, 5)      // also fits: overwrites the element t just appended!
v := append(u, 6)      // exceeds capacity: new array, no longer shared
v[0] = 42
Rust
// Rust: assignment and passing MOVE non-Copy values; the old name becomes unusable
fn consume(v: Vec<i32>) -> usize { v.len() }
fn main() {
    let v = vec![1, 2, 3];
    let n = consume(v);          // ownership moves into consume
    println!("{n} {:?}", v);     // use after move: rejected at compile time
}
C++
// C++: copies are deep by default and can be expensive; std::move transfers resources
Tracker a;                       // owns a 1,000,000-int vector (4 MB)
Tracker b = a;                   // copy constructor: duplicates 4 MB
Tracker c = std::move(a);        // move constructor: steals the buffer, a is left empty
Tracker d = make();              // return value: copy elided entirely (NRVO)
v.push_back(b); v.push_back(std::move(c));
Text
C struct copy:      a.x=1 b.x=99
C copied pointer:   v.data[0]=99
Java int copy:      a=1 b=99
Java list alias:    xs=[99, 2, 3]
Java Integer ==:    127==127 true, 128==128 false, equals true
Go array copy:      [1 2 3] [99 2 3]
Go append aliasing: [0 0 0 5] [0 0 0 5]
after realloc:      [0 0 0 5] [42 0 0 5 6]
error[E0382]: borrow of moved value: `v`
 --> own.rs:5:26
3 |     let v = vec![1, 2, 3];
  |         - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait
4 |     let n = consume(v);          // ownership moves into consume
  |                     - value moved here
5 |     println!("{n} {:?}", v);     // use after move: rejected at compile time
  |                          ^ value borrowed here after move
C++ copies=2 moves=2; a.data.size()=0 after move

Read each line as a rule you can now state precisely:

  • C copies whatever bytes are in the struct. If those bytes are a pointer, you copied an address, not the data: a "value" type with reference behaviour inside.
  • Java == on objects compares identity (same object?), not value. Integer caches −128…127, so 127 == 127 is true by accident of the cache and 128 == 128 is false. Always use equals for values; this bug survives code review because it passes tests with small numbers.
  • Go t and u both show 5: two appends on the same slice wrote to the same backing slot. Once capacity is exceeded, append allocates a new array and the aliasing silently stops. Whether two slices share memory depends on capacity, which is invisible at the call site. Copy explicitly (slices.Clone) when you need independence.
  • Rust turns the aliasing question into a compile error: after a move there is exactly one owner, and the compiler even suggests borrowing (&Vec<i32>) instead.
  • C++ counts: two 4 MB copies happened where the code said copy, two cheap moves where it said std::move, and zero for the return value (copy elision is guaranteed in many return cases since C++17). After the move, a is "valid but unspecified" (empty here).

How deep can recursion go?

Each call needs a stack frame, and stacks are finite. Recursing until something breaks, per language:

Text
C (8 MB stack, 64 B of locals per frame, -O0):   crashed (SIGSEGV) at depth 74610
Java (default thread stack):                     StackOverflowError at depth 22142
Java with -Xss16m:                               StackOverflowError at depth 416469
Python:                                          recursion limit 1000 → RecursionError
Go (stack limit set to 64 MB):                   runtime: goroutine stack exceeds 67108864-byte limit
                                                 fatal error: stack overflow
Rust:                                            thread 'main' has overflowed its stack (abort)

The failure modes differ as much as the depths. C gets a segmentation fault (the stack ran into a guard page; chapter 8), catchable only with tricks like an alternate signal stack. Java throws a catchable error, so a server survives a runaway recursion in one request. Python refuses at a configurable counter (1,000) long before the real stack is at risk. Go grows goroutine stacks dynamically (they start at a few KB), so recursion is very deep by default, but exhaustion is a fatal error that kills the whole process, not a recoverable panic. Rust aborts the process with a clear message.

Practical consequences: recursion over user-controlled depth (parsing nested JSON, walking a tree a user built, a recursive descent parser) is a denial-of-service risk in every language; convert it to iteration with an explicit stack, or enforce a depth limit. Tail recursion doesn't save you in C, Java, Go or Python (none guarantee tail-call elimination; chapter 4).

What error handling costs

Exceptions are cheap to set up and expensive to throw, mostly because constructing an exception captures a stack trace. Measured on JDK 21, a failure detected 50 frames deep and reported to the top, one million times (after warm-up):

Java
static final class ParseFailure extends Exception {
    ParseFailure(String m, boolean trace) { super(m, null, false, trace); }   // writableStackTrace flag
}
static int parseCode(String s) { return s.isEmpty() ? -1 : s.length(); }      // sentinel result
static int parseExc(String s, boolean trace) throws ParseFailure {
    if (s.isEmpty()) throw new ParseFailure("empty", trace);
    return s.length();
}
Text
per failure: return code 103 ns, exception with stack trace 5168 ns, without 1749 ns
per failure: return code 116 ns, exception with stack trace 4434 ns, without 1838 ns   (second run)

About 40–50× more per failure for an exception with a stack trace, and still ~15× without one (the unwinding itself costs). This doesn't mean "avoid exceptions": for genuinely exceptional failures the cost is irrelevant, and the stack trace is worth far more than 5 µs when you debug. It means don't use exceptions for expected control flow in hot paths (parsing user input that's often invalid, cache misses, "not found" lookups), where Result-style values (Rust's Result, Go's error, Zig's error unions, C++23 std::expected, or Java returning Optional) are both faster and more honest about the outcome.

Serialization across languages: the 2⁵³ trap

Values must survive leaving the program. A classic production bug: a Java, Go or Rust backend uses 64-bit integer ids; a JavaScript client parses the JSON:

JavaScript
const o = JSON.parse('{"orderId": 9007199254740993, "amount": 0.1}');     // 2^53 + 1
console.log("parsed orderId:", o.orderId, "| printed back:", String(o.orderId) === "9007199254740993" ? "intact" : "CHANGED",
            "| safe integer?", Number.isSafeInteger(o.orderId));
console.log("as string field:", JSON.parse('{"orderId": "9007199254740993"}').orderId, "→ BigInt", BigInt("9007199254740993") + 1n);
Text
parsed orderId: 9007199254740992 | printed back: CHANGED | safe integer? false
as string field: 9007199254740993 → BigInt 9007199254740994n

JavaScript numbers are IEEE 754 doubles (chapter 6), which represent every integer exactly only up to 2⁵³. Above that, JSON.parse silently rounds: the client now refers to a different order. No error, no warning. Twitter hit exactly this with tweet ids and added an id_str field; the general fix is to serialise 64-bit identifiers as strings in JSON APIs (protobuf's JSON mapping does this for int64 by default). The lesson for serialization generally: the format's type system and every consumer's type system must agree, or data changes in transit.

Revision sheet: programming fundamentals

Key ideas

  • A program is source text that is translated (compiled, interpreted, or both) into instructions a machine runs; the stages and their errors are in chapter 10.
  • A variable is a name bound to a value stored somewhere; its type decides how the bits are interpreted and which operations are allowed.
  • Value vs reference semantics: assigning a primitive copies it; assigning an object (Java, Python, Go maps/slices, JS objects) copies a reference, so both names see changes.
  • Expressions produce values; statements do things. Operator precedence and integer vs float division differ by language (Python 7 // 2 == 3, -7 // 2 == -4; C/Java/Go truncate: -7 / 2 == -3).
  • Control flow: sequence, selection (if, switch/match), iteration (for, while), plus early exit (break, continue, return) and exceptions.
  • Functions take parameters and return results; each call gets a stack frame with its locals; recursion needs a base case and progress toward it.
  • Abstraction hides how behind what: interfaces, traits and protocols let code depend on capabilities rather than concrete types (polymorphism).
  • Errors are handled by exceptions (Java, Python, C++), error values (Go, C), or result types (Rust Result, Zig error unions). Whatever the mechanism, decide where each error is handled and never silently ignore one.
  • Immutability and ownership reduce bugs: values that can't change can be shared freely; Rust makes ownership explicit and checks it at compile time.
  • Static typing catches type errors before running; dynamic typing finds them when the line executes. Strong vs weak is about implicit conversions, a separate axis.
  • Testing: unit tests check small pieces against known answers and properties; a debugger or well-placed prints show the actual state when reality and expectation differ.

Numbers to remember

  • Default thread stack: about 8 MB on Linux (main thread), 1 MB typical for JVM threads (-Xss); deep recursion runs out around tens of thousands of frames.
  • Python's default recursion limit: 1,000.
  • Java int is 32-bit (about ±2.1 billion), long 64-bit; Python int is unbounded.

Pitfalls

  • = (assignment) vs == (comparison); == vs .equals() for Java strings and objects.
  • Off-by-one: range(1, n) stops at n − 1; the last index is len − 1.
  • Mutating a list while iterating over it; mutable default arguments in Python (def f(x=[])).
  • Integer division where you meant real division (5 / 2 is 2 in C and Java).
  • Swallowing exceptions (catch (Exception e) {}) hides the bug instead of fixing it.
  • Comparing floats with == (chapter 6).

Glossary

  • Binding: the association between a name and a value or storage location.
  • Scope: the region of code where a name is visible.
  • Side effect: any change a function makes beyond returning a value (printing, writing a file, mutating an argument).
  • Pure function: same inputs, same output, no side effects.
  • Stack frame: the block of stack memory holding one call's parameters, locals and return address.
  • Heap: memory for values that outlive the call that created them.
  • Interface / trait: a named set of operations a type promises to provide.
  • Serialization: turning in-memory data into bytes or text (JSON, binary) and back.
  • Paradigm: a style of organising programs: imperative, object-oriented, functional, declarative.