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.
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:
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
Two things confuse almost every beginner, so settle them now:
=means "store", not "is equal to".lunches = lunches - 1is 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.
totalwas computed fromlunchesonce; if you later changelunches,totaldoes 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:
$ 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 / 2is3(the fraction is thrown away). Write7 / 2.0to get3.5. Python 3's/always gives a float;//is integer ("floor") division. %is the remainder (modulo):7 % 2is1. 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 // 2down to-4(and makes-7 % 2equal1), while Java and C round towards zero (-3and-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:
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)gives0, 1, 2, 3, 4(five numbers, starting at 0, stopping before 5).
Trace this loop by hand before reading the table:
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):
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
120and0.05are given the parameter namespriceandratefor the duration of the call. returnsends 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"], somenu[0]is"biryani"andmenu[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}, soprices["dal"]is90.
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:
- 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?")
- Work a small example by hand. If you can't solve it on paper, you can't program it.
- Write the steps in plain language (pseudocode), then refine them until each step is obviously one or two lines of code.
- Write the code, one small piece at a time, running it after each piece.
- 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.
- 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.
- 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. - 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"))
public class Ex {
static Integer largest(int[] numbers) {
if (numbers.length == 0) return null; // an empty array has no largest number
int best = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > best) best = numbers[i];
}
return best;
}
static int countVowels(String text) {
int count = 0;
for (char ch : text.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(ch) >= 0) count++;
}
return count;
}
public static void main(String[] args) {
for (int n = 1; n <= 15; n++) {
if (n % 15 == 0) System.out.println("FizzBuzz");
else if (n % 3 == 0) System.out.println("Fizz");
else if (n % 5 == 0) System.out.println("Buzz");
else System.out.println(n);
}
System.out.println(largest(new int[]{12, 7, 31, 4}) + " " + largest(new int[]{-5, -2, -9}) + " " + largest(new int[]{}));
System.out.println(countVowels("Hyderabadi Biryani"));
}
}
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int largest(const int *numbers, int n, int *out) { // returns 0 if the array is empty
if (n == 0) return 0;
int best = numbers[0];
for (int i = 1; i < n; i++)
if (numbers[i] > best) best = numbers[i];
*out = best;
return 1;
}
int count_vowels(const char *text) {
int count = 0;
for (int i = 0; text[i] != '\0'; i++) // a C string ends with the character '\0'
if (strchr("aeiou", tolower((unsigned char)text[i]))) count++;
return count;
}
int main(void) {
for (int n = 1; n <= 15; n++) {
if (n % 15 == 0) printf("FizzBuzz\n");
else if (n % 3 == 0) printf("Fizz\n");
else if (n % 5 == 0) printf("Buzz\n");
else printf("%d\n", n);
}
int a[] = {12, 7, 31, 4}, b[] = {-5, -2, -9}, result;
if (largest(a, 4, &result)) printf("%d ", result);
if (largest(b, 3, &result)) printf("%d ", result);
if (!largest(NULL, 0, &result)) printf("(empty) ");
printf("\n%d\n", count_vowels("Hyderabadi Biryani"));
return 0;
}
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 returnsnull(so the return type isInteger, an object, rather thanint), 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 (yisn'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:
javacemits.classbytecode, and the JVM interprets it, profiles it, and JIT-compiles hot methods with its C1 and C2 compilers.
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
.cor.cppfile, after the preprocessor has pasted in its#included headers, is one translation unit. A header declares (int add(int, int);) and exactly one.cfile 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
rustcsplits 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 frommainoutward, so code that is never referenced is never even type-checked. - Java: each
.javafile holds one public top-level class and compiles to a.classfile. Linking happens lazily at run time when the JVM resolves a class reference.
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:
- Name: what you write in code. It exists only at compile time, unless debug info keeps it.
- Location: where the bits live. That can be a register, a stack slot, the heap, or the static data segment.
- 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
staticlocals, Javastaticfields (per class loader) and Ruststaticitems 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_localin C23), C++ hasthread_local, Java hasThreadLocal, Rust hasthread_local!, and Zig hasthreadlocal 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);
}
#include <memory>
#include <print> // C++23
int counter = 0;
void f() {
static int calls = 0;
int local = 5;
auto heap = std::make_unique<int>(local + ++calls); // freed automatically
std::println("{}", *heap);
} // unique_ptr destructor runs here: RAII
class Demo {
static int counter = 0; // one per loaded class
void f() {
int local = 5; // primitive: lives in the frame
Integer boxed = local + 1; // object: on the heap, GC-managed
System.out.println(boxed);
} // no free: unreachable objects are collected
}
static COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
fn f() {
let local = 5; // stack
let heap = Box::new(local + 1); // heap, owned by `heap`
println!("{heap}");
} // `heap` dropped → memory freed
const std = @import("std");
var counter: u32 = 0; // container-level: static storage
fn f(allocator: std.mem.Allocator) !void {
const local: u32 = 5; // stack
const heap = try allocator.create(u32); // heap: you choose the allocator
defer allocator.destroy(heap); // and you free it
heap.* = local + 1;
std.debug.print("{d}\n", .{heap.*});
}
package main
import "fmt"
var counter int // package-level: static
func f() *int {
local := 5
p := &local // legal! escape analysis moves `local` to the heap
fmt.Println(*p)
return p // still valid after return; the GC keeps it alive
}
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:
- Immutable binding: this name can't be reassigned (Java
final, Rustlet, Zigconst, JavaScriptconst). - Read-only view: you can't modify through this pointer, but someone else might (C/C++
const T*, Rust&Tusually). - 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];
constexpr int square(int x) { return x * x; } // may run at compile time
consteval int must_ct(int x) { return x + 1; } // must run at compile time (C++20)
constinit int g = square(4); // statically initialised, still mutable
const int* p; // pointer to const int: can't write *p
int* const q = nullptr; // const pointer: can't reseat q
std::array<int, square(4)> a; // 16 elements, computed by the compiler
final int x = 5; // binding can't change
static final int MAX = 100; // compile-time constant: inlined into callers!
final List<String> names = new ArrayList<>();
names.add("ok"); // allowed: `final` is about the reference, not the object
List<String> frozen = List.of("a", "b"); // immutable collection: add() throws
const MAX: usize = 100; // inlined everywhere it's used
static GREETING: &str = "hi"; // one fixed address, 'static lifetime
const fn square(x: u32) -> u32 { x * x }
const AREA: u32 = square(12); // evaluated by the compiler
let n = 5; // immutable by default
let mut m = 5; // opt in to mutation
m += n;
const std = @import("std");
const max = 100; // comptime_int: arbitrary precision
fn square(x: u32) u32 { return x * x; }
const area = square(12); // container-level const: evaluated at compile time
fn f() u32 { return comptime square(12); } // inside a function, `comptime` forces it
var table: [square(4)]u8 = undefined; // any function can run at comptime
fn Matrix(comptime n: usize) type { // types are comptime values
return struct { data: [n][n]f32 };
}
const Max = 100 // untyped constant: exact, arbitrary precision
const Pi = 3.14159265358979323846264338327950288 // kept exact until used
type Weekday int
const (
Sunday Weekday = iota // 0
Monday // 1 (iota increments per line)
Tuesday // 2
)
var x float32 = Pi // converted (and rounded) only here
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):
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.
ifis a statement, so you need the ternaryc ? a : bfor a conditional value. Go has no ternary at all, by design. - Rust and Zig are expression-oriented. Blocks,
if,match/switchand evenloopproduce 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 };
const grade: u8 = if (score >= 90) 'A' else if (score >= 80) 'B' else 'C';
const parsed = std.fmt.parseInt(i32, s, 10) catch 0;
// labelled blocks return values with `break :label value`
const area = blk: {
const w = 3;
const h = 4;
break :blk w * h;
};
// Go has no conditional expression: use a statement
var grade byte
switch {
case score >= 90:
grade = 'A'
case score >= 80:
grade = 'B'
default:
grade = 'C'
}
char grade = score >= 90 ? 'A' : score >= 80 ? 'B' : 'C';
// switch *expressions* (Java 14+) yield values and must be exhaustive
String kind = switch (day) {
case SATURDAY, SUNDAY -> "weekend";
default -> "weekday";
};
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,@remor@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(),fruns 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 callgfirst.i = i++ + 1;is undefined because it modifiesitwice 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/orin Zig) evaluate the right side only if needed. Code likep != NULL && p->x > 0relies on this. - Bitwise
& | ^ ~ << >>operate on bits (chapter 6 covers them in depth). Some traps: in C,x & 1 == 0parses asx & (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 << 33equalsx << 1forint). 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 whynew String("a") == new String("a")isfalse. Rust==callsPartialEq::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++ callsoperator==.
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
long big = 1L << 40;
int small = (int) big; // explicit narrowing: keeps the low 32 bits → 0
double d = 3.9;
int n = (int) d; // 3
int x = 'A' + 1; // char widens to int implicitly: 66
let big: u64 = 1 << 40;
let small = big as u32; // `as` truncates silently: 0
let checked = u32::try_from(big); // Err(TryFromIntError) — prefer this
let n = 3.9_f64 as i32; // 3 (float→int `as` saturates; NaN → 0)
// let bad: u32 = 5i32; // compile error: no implicit conversion
const big: u64 = 1 << 40;
const small: u32 = @truncate(big); // explicit truncation
const safe: u32 = @intCast(big); // checked: panics in safe modes if it doesn't fit
const n: i32 = @intFromFloat(3.9); // 3; out-of-range is illegal behaviour
const wider: u64 = small; // implicit *widening* is allowed (lossless)
var big uint64 = 1 << 40
small := uint32(big) // conversion truncates: 0
n := int(3.9) // compile error for a constant! constants must fit exactly
f := 3.9
m := int(f) // 3 at run time
// var y int64 = small // compile error: mismatched types, convert explicitly
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
}
sealed interface Shape permits Circle, Rect, Tri {}
record Circle(double r) implements Shape {}
record Rect(double w, double h) implements Shape {}
record Tri(double a, double b, double c) implements Shape {}
static double area(Shape s) {
return switch (s) { // exhaustive over the sealed hierarchy
case Circle(double r) -> Math.PI * r * r;
case Rect(double w, double h) when w == h -> w * w;
case Rect(double w, double h) -> w * h;
case Tri(double a, double b, double c) -> {
double p = (a + b + c) / 2;
yield Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
};
}
const Shape = union(enum) {
circle: f64,
rect: struct { w: f64, h: f64 },
fn area(self: Shape) f64 {
return switch (self) { // exhaustive: missing a tag is a compile error
.circle => |r| std.math.pi * r * r,
.rect => |r| r.w * r.h,
};
}
};
type Shape interface{ Area() float64 }
type Circle struct{ R float64 }
type Rect struct{ W, H float64 }
func describe(s Shape) string {
switch v := s.(type) { // type switch: not exhaustive, needs default
case Circle:
return fmt.Sprintf("circle r=%v", v.R)
case Rect:
return fmt.Sprintf("rect %vx%v", v.W, v.H)
default:
return "unknown"
}
}
enum Color { RED, GREEN, BLUE };
const char *name(enum Color c) {
switch (c) {
case RED: return "red";
case GREEN: return "green"; // falls through to BLUE if you forget `return`/`break`
case BLUE: return "blue";
}
return "?"; // the compiler can't prove c is in range: enums are just ints
}
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 withbegin()andend(). C++20 adds ranges and views for lazy pipelines. - Java: the classic
for, plus enhanced-for over anyIterable, plus Streams (chapter 37 of the roadmap). - Rust:
loop,while,for x in iter.foronly works with iterators; there is no C-stylefor. Ranges are0..n(exclusive) and0..=n(inclusive). - Zig:
while (cond) : (step),for (slice) |item|,for (0..n) |i|, andfor (a, b) |x, y|to walk two slices in lockstep. A loop can have anelsebranch that runs when the loop completes withoutbreak. - Go: one keyword,
for, does everything:for i := 0; i < n; i++,for cond,for {}, andfor 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
int sum = 0;
for (int x : v) sum += x;
// C++20 ranges: lazy pipeline, nothing runs until iterated
for (int sq : v | std::views::filter([](int x){ return x % 2; })
| std::views::transform([](int x){ return x * x; }))
sum += sq;
int sum = 0;
for (int x : list) sum += x;
int odds = list.stream().filter(x -> x % 2 != 0).mapToInt(x -> x * x).sum();
let sum: i32 = v.iter().sum();
let odds: i32 = v.iter().filter(|&&x| x % 2 != 0).map(|x| x * x).sum();
for (i, x) in v.iter().enumerate() { println!("{i}: {x}"); }
'outer: for row in grid { for cell in row { if *cell == 0 { break 'outer; } } }
var sum: i32 = 0;
for (items) |x| sum += x;
for (items, 0..) |x, i| std.debug.print("{d}: {d}\n", .{ i, x });
var i: usize = 0;
while (i < items.len) : (i += 1) {
if (items[i] == 0) break;
} else {
std.debug.print("no zero found\n", .{}); // runs only if the loop didn't break
}
sum := 0
for _, x := range xs {
sum += x
}
for i := range 10 { // Go 1.22+
fmt.Println(i)
}
outer:
for _, row := range grid {
for _, cell := range row {
if cell == 0 { break outer }
}
}
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
}
int process(const std::string& path) {
std::ifstream f(path); // closed by destructor
if (!f) return -1;
std::vector<char> buf(4096); // freed by destructor
f.read(buf.data(), buf.size());
return f.gcount() ? 0 : -1; // every return path cleans up
}
static int process(Path path) throws IOException {
try (var in = Files.newInputStream(path)) { // closes in.close() on any exit
byte[] buf = in.readNBytes(4096);
return buf.length > 0 ? 0 : -1;
}
}
fn process(path: &str) -> std::io::Result<usize> {
let mut f = std::fs::File::open(path)?; // `?` returns early on error
let mut buf = vec![0u8; 4096];
let n = std::io::Read::read(&mut f, &mut buf)?;
Ok(n) // f and buf dropped here, or at any `?`
}
fn process(allocator: std.mem.Allocator, path: []const u8) ![]u8 {
const file = try std.fs.cwd().openFile(path, .{});
defer file.close(); // always
const buf = try allocator.alloc(u8, 4096);
errdefer allocator.free(buf); // only if we return an error below
const n = try file.readAll(buf);
if (n == 0) return error.EmptyFile; // errdefer frees buf
return buf[0..n]; // success: caller now owns buf
}
func process(path string) (int, error) {
f, err := os.Open(path)
if err != nil {
return 0, err
}
defer f.Close() // runs when process returns (LIFO with other defers)
buf := make([]byte, 4096)
return f.Read(buf)
}
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 |
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
void by_value(std::vector<int> v) { v.push_back(1); } // copies the whole vector
void by_ref(std::vector<int>& v) { v.push_back(1); } // caller sees it
void read_only(const std::vector<int>& v) { /* no copy, no mutation */ }
void sink(std::vector<int>&& v) { auto mine = std::move(v); } // steals the buffer
fn take(v: Vec<i32>) { } // ownership moves in; caller can't use v after
fn borrow(v: &Vec<i32>) { } // read-only loan
fn edit(v: &mut Vec<i32>) { v.push(1); } // exclusive loan: caller sees the push
let mut v = vec![1, 2];
borrow(&v);
edit(&mut v);
take(v);
// println!("{:?}", v); // compile error: value used after move
func appendOne(s []int) { s = append(s, 1) } // caller's slice header unchanged!
func setFirst(s []int) { s[0] = 99 } // caller sees it: shared backing array
func appendOnePtr(s *[]int) { *s = append(*s, 1) } // caller sees it
// idiom: return the new slice instead → s = append(s, x)
void bump(int n) { n++; } // copy: no effect on caller
void bump_p(int *n) { (*n)++; } // caller passes &x
void fill(int a[10]) { a[0] = 1; } // really `int *a`: caller's array IS modified
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::tuplewith 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), thenlet (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 ofvalue, err :=.
Overloading, default arguments and variadics
- Overloading (same name, different parameter types): C++ and Java have it. C has none, though C11
_Genericdispatches on type in macros. Rust, Zig and Go have none, by design: Rust uses traits and Go uses different names (strconv.Itoaandstrconv.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
Defaultpatterns (Rust..Default::default()), options structs (Go and Zig:.{ .timeout = 30 }relies on default field values). - Variadics: C
...withva_list(no type safety:printf("%d", 3.0)is UB). C++ has variadic templates, which are type-safe. Java hasString... args(it's an array). Go hasargs ...int(a slice). Rust has no variadic functions, so it uses macros (println!,vec!). Zig uses tuples withanytype: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; }
int k = 10;
auto by_copy = [k](int x) { return x + k; }; // copies k now
auto by_ref = [&k](int x) { return x + k; }; // refers to k: dangles if k dies first!
auto counter = [n = 0]() mutable { return ++n; }; // init-capture with its own state
std::function<int(int)> f = by_copy; // type-erased, may heap-allocate
int k = 10; // must be effectively final to be captured
Function<Integer, Integer> add = x -> x + k; // captures a *copy* of k
// k++; // compile error: k is captured
Supplier<Integer> counter = new Supplier<>() { // mutable state needs a field or array
int n = 0;
public Integer get() { return ++n; }
};
let k = 10;
let add = |x: i32| x + k; // borrows k (Fn)
let mut n = 0;
let mut counter = || { n += 1; n }; // mutably borrows n (FnMut)
let s = String::from("hi");
let consume = move || s.len(); // takes ownership of s (FnOnce if it consumes)
// Fn: call many times, shared; FnMut: many times, exclusive; FnOnce: at least once
fn make_adder(k: i32) -> impl Fn(i32) -> i32 { move |x| x + k }
// Zig has no closures. Pass a context explicitly, or use a struct with a method.
const Adder = struct {
k: i32,
fn call(self: Adder, x: i32) i32 { return x + self.k; }
};
const add10 = Adder{ .k = 10 };
const r = add10.call(5); // 15
fn apply(ctx: anytype, x: i32) i32 { return ctx.call(x); } // static duck typing
k := 10
add := func(x int) int { return x + k } // captures k by reference
k = 20
fmt.Println(add(1)) // 21: sees the update
func counter() func() int {
n := 0 // escapes to the heap, owned by the closure
return func() int { n++; return n }
}
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:
- A base case that returns without recursing.
- Progress: each recursive call moves toward the base case, for example a smaller
nor a shorter list.
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
becomekeyword 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() }
fn sumTail(v: []const i64, acc: i64) i64 {
if (v.len == 0) return acc;
return @call(.always_tail, sumTail, .{ v[1..], acc + v[0] }); // guaranteed constant stack
}
// Explicit stack: the standard way to remove deep recursion
static int countNodes(Node root) {
int count = 0;
Deque<Node> stack = new ArrayDeque<>();
if (root != null) stack.push(root);
while (!stack.isEmpty()) {
Node n = stack.pop();
count++;
for (Node c : n.children) stack.push(c);
}
return count;
}
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 'é'
s := "héllo"
fmt.Println(len(s)) // 6 bytes
fmt.Println(utf8.RuneCountInString(s)) // 5 runes
for i, r := range s { // i jumps 0,1,3,4,5 — r is a rune
fmt.Println(i, string(r))
}
b := s[1] // a byte (0xC3), not 'é'
String s = "héllo";
s.length(); // 5 UTF-16 units (é fits in one)
"👍".length(); // 2! emoji are surrogate pairs
"👍".codePointCount(0, 2); // 1
s.charAt(1); // 'é'
// Strings are immutable: concatenation in a loop builds new objects
var sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.append(i);
char s[] = "h\xc3\xa9llo"; // é as two UTF-8 bytes
size_t n = strlen(s); // 6: counts bytes until '\0'
char buf[4];
strcpy(buf, s); // overflow! 7 bytes into 4: classic memory-safety bug
snprintf(buf, sizeof buf, "%s", s); // bounded: writes "h\xc3\xa9" + '\0' (truncated mid-character)
const s = "héllo"; // *const [6:0]u8, coerces to []const u8
std.debug.print("{d}\n", .{s.len}); // 6
var it = (try std.unicode.Utf8View.init(s)).iterator();
while (it.nextCodepoint()) |cp| std.debug.print("{u}", .{cp});
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.
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
Who controls layout?
- C and C++ keep declaration order, so field order is part of the ABI.
#pragma packor__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
structfields.extern structgives C layout, andpacked structgives 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
fieldalignmentsuggest 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:
staticat 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++:
namespacefor naming, anonymous namespaces for internal linkage, andpublic/private/protectedfor class members. C++20 modules addexport. - Java:
public,protected, package-private (no keyword), andprivate. Since Java 9, JPMS modules add a stronger layer: amodule-info.javaexportsonly chosen packages, sopublicclasses in unexported packages are invisible outside the module. - Rust: everything is private by default.
pubexports, andpub(crate)andpub(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.
Exportedvsunexported, at package level. Aninternal/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:
- Procedural abstraction: name a computation (a function) so callers don't repeat the steps.
- 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;andStack *stack_new(void);, and the struct's fields are defined only in the.cfile. Callers can't touch the internals because they can't see them. - 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
Tthat can be compared"), such as Java<T extends Comparable<T>>, RustT: Ord, C++20std::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."
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
}
struct Shape { // abstract base class
virtual ~Shape() = default; // virtual destructor: required!
virtual double area() const = 0; // pure virtual
};
struct Circle : Shape { double r; double area() const override { return 3.14159 * r * r; } };
// C++20 concepts: compile-time interface, no vtable
template <typename T>
concept HasArea = requires(const T& t) { { t.area() } -> std::convertible_to<double>; };
double twice(const HasArea auto& s) { return 2 * s.area(); }
trait Shape {
fn area(&self) -> f64;
fn describe(&self) -> String { format!("area={}", self.area()) } // default
}
struct Circle { r: f64 }
impl Shape for Circle { fn area(&self) -> f64 { std::f64::consts::PI * self.r * self.r } }
fn total_static<T: Shape>(xs: &[T]) -> f64 { xs.iter().map(|s| s.area()).sum() } // monomorphised
fn total_dyn(xs: &[Box<dyn Shape>]) -> f64 { xs.iter().map(|s| s.area()).sum() } // vtable
// you can also implement *your* trait for *foreign* types: impl Shape for f64 { … }
type Shape interface{ Area() float64 } // structural: no `implements` keyword
type Circle struct{ R float64 }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R } // Circle now satisfies Shape
func total(xs []Shape) float64 {
sum := 0.0
for _, s := range xs { sum += s.Area() } // dynamic dispatch via itab
return sum
}
var _ Shape = Circle{} // compile-time assertion that Circle implements Shape
// Zig: no interfaces in the language. Two idioms:
// 1) compile-time duck typing with anytype (like C++ templates)
fn totalArea(shapes: anytype) f64 {
var sum: f64 = 0;
for (shapes) |s| sum += s.area();
return sum;
}
// 2) a hand-written vtable for runtime polymorphism (how std.mem.Allocator works)
const Shape = struct {
ptr: *anyopaque,
areaFn: *const fn (*anyopaque) f64,
fn area(self: Shape) f64 { return self.areaFn(self.ptr); }
};
/* C: the vtable is just a struct of function pointers you build yourself */
typedef struct Shape Shape;
typedef struct { double (*area)(const Shape *); } ShapeVTable;
struct Shape { const ShapeVTable *vt; };
typedef struct { Shape base; double r; } Circle;
static double circle_area(const Shape *s) { const Circle *c = (const Circle *)s; return 3.14159 * c->r * c->r; }
static const ShapeVTable CIRCLE_VT = { circle_area };
/* usage: Circle c = { { &CIRCLE_VT }, 2.0 }; ((Shape*)&c)->vt->area((Shape*)&c); */
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
fn largest<T: PartialOrd + Copy>(xs: &[T]) -> T {
let mut m = xs[0];
for &x in xs { if x > m { m = x; } }
m
}
largest(&[1, 5, 3]); // compiler emits largest::<i32>
largest(&[1.0, 0.5]); // and a separate largest::<f64>
template <typename T>
T largest(std::span<const T> xs) { // checked only when instantiated (pre-concepts)
T m = xs[0];
for (const T& x : xs) if (x > m) m = x;
return m;
}
func Largest[T cmp.Ordered](xs []T) T {
m := xs[0]
for _, x := range xs {
if x > m { m = x }
}
return m
}
fn largest(comptime T: type, xs: []const T) T { // T is just a comptime parameter
var m = xs[0];
for (xs) |x| { if (x > m) m = x; }
return m;
}
const r = largest(i32, &.{ 1, 5, 3 });
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
unreachablereached. 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");
#include <expected> // C++23
#include <fstream>
#include <string>
enum class PortError { Io, Parse, Range };
std::expected<int, PortError> read_port(const std::string& path) {
std::ifstream f(path);
if (!f) return std::unexpected(PortError::Io);
int v;
if (!(f >> v)) return std::unexpected(PortError::Parse);
if (v < 1 || v > 65535) return std::unexpected(PortError::Range);
return v;
}
// or the exception style: throw std::runtime_error("bad port"); catch in main
static int readPort(Path path) throws IOException { // checked: callers must handle
String text = Files.readString(path).strip();
int v;
try {
v = Integer.parseInt(text); // throws NumberFormatException (unchecked)
} catch (NumberFormatException e) {
throw new IllegalArgumentException("not a number: " + text, e); // keep the cause
}
if (v < 1 || v > 65535) throw new IllegalArgumentException("port out of range: " + v);
return v;
}
use std::{fs, num::ParseIntError};
#[derive(Debug)]
enum PortError { Io(std::io::Error), Parse(ParseIntError), Range(u32) }
impl From<std::io::Error> for PortError { fn from(e: std::io::Error) -> Self { PortError::Io(e) } }
impl From<ParseIntError> for PortError { fn from(e: ParseIntError) -> Self { PortError::Parse(e) } }
fn read_port(path: &str) -> Result<u16, PortError> {
let text = fs::read_to_string(path)?; // `?` = return Err(e.into()) if Err
let v: u32 = text.trim().parse()?;
u16::try_from(v).ok().filter(|&p| p != 0).ok_or(PortError::Range(v))
}
// apps often use `anyhow::Result<T>`, libraries `thiserror` to derive these impls
const PortError = error{ OutOfRange };
fn readPort(allocator: std.mem.Allocator, path: []const u8) !u16 { // inferred error set
const text = try std.fs.cwd().readFileAlloc(allocator, path, 64); // may fail: FileNotFound, …
defer allocator.free(text);
const v = try std.fmt.parseInt(u32, std.mem.trim(u8, text, " \r\n"), 10); // InvalidCharacter, Overflow
if (v == 0 or v > 65535) return PortError.OutOfRange;
return @intCast(v);
}
// caller: const port = readPort(a, "p.conf") catch |err| switch (err) {
// error.FileNotFound => 8080,
// else => return err,
// };
var ErrRange = errors.New("port out of range")
func readPort(path string) (int, error) {
b, err := os.ReadFile(path)
if err != nil {
return 0, fmt.Errorf("read port: %w", err) // %w wraps: errors.Is/As still see it
}
v, err := strconv.Atoi(strings.TrimSpace(string(b)))
if err != nil {
return 0, fmt.Errorf("parse port: %w", err)
}
if v < 1 || v > 65535 {
return 0, fmt.Errorf("%d: %w", v, ErrRange)
}
return v, nil
}
// caller: if errors.Is(err, os.ErrNotExist) { … }
Designing errors well
Whatever the mechanism, the same rules apply:
- 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 usesanyhow's.context(…), Java uses exception chaining (new X(msg, cause)), and Zig has error return traces built in, which show everytrythe error passed through. - Let callers distinguish errors they can act on. Use specific types, codes or sentinels (
os.ErrNotExist,io::ErrorKind::NotFound,error.FileNotFound), not just strings. - 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.
- Fail fast on bugs. Assertions,
panic,unreachableandObjects.requireNonNullstop the program close to the cause. - 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:
- Immutable binding: the variable can't be reassigned (
final,let,constin Zig). - Shallow immutability: the object's fields can't be reassigned, but objects they reference can change. A Java
recordholding aListis like this. - Deep immutability: nothing reachable can change. Java
String, Gostring, 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;leavesaunchanged. Each variable owns independent data. C structs, C++ objects, Go structs and arrays, Rust (where a "copy" is a move for non-Copytypes), Zig, and Java primitives all behave this way. - Reference semantics: assignment shares.
b = a; b.x = 5;changes whatasees, 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!
class P { int x; P(int x) { this.x = x; } }
P a = new P(1);
P b = a; // copies the reference: same object
b.x = 5; // a.x is now 5
int i = 1;
int j = i; // primitives copy
j = 5; // i is still 1
struct P { int x; };
P a{1};
P b = a; // copy constructor: independent
b.x = 5; // a.x still 1
P& r = a; // explicit reference: alias
r.x = 7; // a.x is 7
std::vector<int> v1{1,2,3};
auto v2 = v1; // deep copy of all elements (can be expensive!)
auto v3 = std::move(v1); // steals the buffer; v1 is now valid-but-unspecified (empty in practice)
#[derive(Clone, Copy)] struct P { x: i32 }
let a = P { x: 1 };
let mut b = a; // Copy type: bitwise copy
b.x = 5; // a.x still 1
let v1 = vec![1, 2, 3];
let v2 = v1; // MOVE: v1 is no longer usable (compile error to touch it)
let v3 = v2.clone(); // explicit deep copy
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:
- Every value has exactly one owner.
- When the owner goes out of scope, the value is dropped.
- You may have either any number of shared borrows
&Tor exactly one mutable borrow&mut T. Never both at once. This is "aliasing XOR mutability." - 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}");
std::vector<int> v{1, 2, 3};
int& first = v[0];
v.push_back(4); // may reallocate: `first` now dangles — compiles fine, UB at run time
std::cout << first; // might print 1, garbage, or crash
auto p = std::make_unique<Widget>();
auto q = std::move(p); // ownership transferred; p is now null
test "no leaks" {
const a = std.testing.allocator; // detects leaks and double frees
var list: std.ArrayList(u32) = .empty; // Zig 0.15: unmanaged by default
defer list.deinit(a);
try list.append(a, 42);
try std.testing.expectEqual(@as(u32, 42), list.items[0]);
}
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.
restrictpromises they don't. Rust's&mutgives 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*withfopen/fread/fprintf.stdoutis line-buffered on a terminal and fully buffered when piped. That's whyprintfoutput 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 addsstd::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/Writetraits,BufReader/BufWriter.stdoutis line-buffered, andprintln!locks stdout on each call, so lock it once for bulk output. - Go: the
io.Reader/io.Writerinterfaces (one method each) compose everything: files, network connections, compressors, hashes. Usebufiofor buffering. - Zig: since 0.15, the
std.Io.Reader/std.Io.Writerinterfaces put the buffer in the interface, and you must callflush().std.debug.printwrites 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)
use std::io::{BufRead, BufReader};
let f = std::fs::File::open("big.log")?;
let n = BufReader::new(f).lines().count();
println!("{n}");
try (var lines = Files.lines(Path.of("big.log"))) { // lazy stream, closes the file
System.out.println(lines.count());
}
FILE *f = fopen("big.log", "r");
if (!f) { perror("open"); return 1; }
int c; long n = 0;
while ((c = getc(f)) != EOF) if (c == '\n') n++; // getc is buffered by stdio
fclose(f);
printf("%ld\n", 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:
\non Unix and\r\non 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)
// add_test.go — same package, file name ends in _test.go
func TestAdd(t *testing.T) {
cases := []struct{ a, b, want int }{{2, 3, 5}, {-1, 1, 0}} // table-driven
for _, c := range cases {
if got := Add(c.a, c.b); got != c.want {
t.Errorf("Add(%d,%d) = %d, want %d", c.a, c.b, got, c.want)
}
}
}
// run: go test ./... go test -race go test -fuzz=FuzzX go test -bench=.
fn add(a: i32, b: i32) i32 { return a + b; }
test "add" {
try std.testing.expectEqual(@as(i32, 5), add(2, 3));
}
// run: zig test add.zig (tests live beside the code they test)
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalcTest {
@Test void adds() { assertEquals(5, Calc.add(2, 3)); }
@Test void overflowWraps() { assertEquals(Integer.MIN_VALUE, Calc.add(Integer.MAX_VALUE, 1)); }
}
// run: mvn test / gradle test (JUnit 5 is a library, not built in)
#include <gtest/gtest.h>
TEST(Calc, Adds) { EXPECT_EQ(add(2, 3), 5); }
// GoogleTest or Catch2 — nothing built into the language; run via ctest
#include <assert.h>
int main(void) {
assert(add(2, 3) == 5); // compiled out when NDEBUG is defined!
return 0; // frameworks: Unity, Check, cmocka, or plain asserts + make test
}
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:
- Read the error. Stack traces, panic messages, compiler errors. Rust's and Zig's compiler errors in particular often contain the fix.
- Print debugging / logging. It's underrated, and the only option in production. Use structured logs (chapter 99).
- Assertions:
assert,debug_assert!,std.debug.assert, Javaassert(disabled unless you pass-ea). - 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. - 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. - Race detectors:
go test -race, TSan. - Core dumps and post-mortems: inspect the crash state after the fact. Java has heap dumps (
jmap) and thread dumps (jstack). git bisect: binary-search history for the commit that introduced a bug, in O(log n) steps.- Record and replay (
rron 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.
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.
unsafeblocks 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.
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
IOmonad, and theOption/Resultchaining 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)
// Rust borrows heavily from ML/Haskell: ADTs, matching, iterators, Option/Result
let total: f64 = shapes.iter().map(Shape::area).sum();
let names: Vec<String> = users.iter()
.filter(|u| u.active)
.map(|u| u.name.to_uppercase())
.collect();
let port = env::var("PORT").ok().and_then(|s| s.parse::<u16>().ok()).unwrap_or(8080);
// Java: streams, lambdas, records and sealed types bring FP into OOP
double total = shapes.stream().mapToDouble(Shape::area).sum();
List<String> names = users.stream()
.filter(User::active)
.map(u -> u.name().toUpperCase())
.toList();
int port = Optional.ofNullable(System.getenv("PORT")).map(Integer::parseInt).orElse(8080);
// Go: functions are values, but the language favours plain loops
var total float64
for _, s := range shapes {
total += s.Area()
}
// generic helpers are possible since 1.18, and iterators since 1.23 (iter.Seq)
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.
-- The same relation, declaratively, in SQL
WITH RECURSIVE ancestors(anc, des) AS (
SELECT parent, child FROM parent_of
UNION
SELECT a.anc, p.child FROM ancestors a JOIN parent_of p ON p.parent = a.des
)
SELECT des FROM ancestors WHERE anc = 'tom';
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
}
use std::{sync::mpsc, thread};
let (tx, rx) = mpsc::channel();
for id in 0..3 {
let tx = tx.clone();
thread::spawn(move || tx.send(id * id).unwrap());
}
drop(tx); // close our copy so rx ends
let mut v: Vec<i32> = rx.iter().collect(); // receives 0, 1, 4 in some order
v.sort();
// Java 21 virtual threads: blocking code, millions of threads
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<Integer>> fs = IntStream.range(0, 10_000)
.mapToObj(i -> exec.submit(() -> { Thread.sleep(100); return i; }))
.toList();
long sum = 0;
for (var f : fs) sum += f.get(); // all 10k sleep concurrently: ~100 ms total
}
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).
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" + 2raisesTypeError). 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 float64andtype Fahrenheit float64are 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);makesvaVec<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,voidin C/C++/Java,voidin Zig, nothing in Go): exactly one value, meaning "no interesting result." - Never / bottom (
!in Rust and Zig'snoreturn, Java has none, C has_Noreturn/[[noreturn]]): no values. It's the type ofpanic!(),loop {}andexit(). Because it has no values, it can stand in for any type, which is whylet x: i32 = if c { 5 } else { panic!() };type-checks. - Top / any (
Objectin Java,anyin Go and TypeScript,void*in C,anyopaquein 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
- 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.
- 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).
- 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.
- 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:
// 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; }
$ 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:
$ 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?
Five programs, one per behaviour:
// 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: 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: 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: 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++: 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));
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.Integercaches −128…127, so127 == 127is true by accident of the cache and128 == 128is false. Always useequalsfor values; this bug survives code review because it passes tests with small numbers. - Go
tanduboth show5: twoappends on the same slice wrote to the same backing slot. Once capacity is exceeded,appendallocates 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,ais "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:
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):
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();
}
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:
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);
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
intis 32-bit (about ±2.1 billion),long64-bit; Pythonintis 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 islen − 1. - Mutating a list while iterating over it; mutable default arguments in Python (
def f(x=[])). - Integer division where you meant real division (
5 / 2is 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.