Programming Languages
Systems programming in C, from types and pointers to memory safety, builds, debugging and threads.
A path through C for programmers who want to understand what runs underneath higher-level languages: types, pointers and manual memory, project structure, the standard library, toolchains, debugging, testing and concurrency. Each subject links the official documentation or a solid reference.
The subjects follow the roadmap.sh C roadmap.
C is a small, compiled, statically typed systems language from the early 1970s that still underpins operating systems, embedded firmware, databases and language runtimes. It gives you direct control over memory and very little protection, so learning it teaches how computers actually run programs.
Kernels (Linux, the BSDs), embedded and microcontroller code, interpreters such as CPython and Lua, databases like SQLite and Redis, and libraries other languages call through a C ABI.
C++ began as C with classes but is now a much larger language with templates, RAII and exceptions. Most C compiles as C++, yet not all — implicit void * conversion and designated initializer rules differ.
Assembly is tied to one CPU's instructions and registers; C abstracts those into portable types, functions and expressions while staying close enough that you can predict the generated code. Compilers now beat hand-written assembly in almost all cases.
All you need is a compiler, an editor and a terminal. Install GCC or Clang, compile with warnings on (-Wall -Wextra), and run the result — the same loop you will use for every program.
On Linux install gcc or clang from the package manager (build-essential on Debian/Ubuntu); on macOS run xcode-select --install for Clang; on Windows use MSYS2 for GCC or Visual Studio's MSVC.
Any editor works, but one backed by a language server (clangd) gives completion, go-to-definition and inline errors. CLion, Visual Studio and Code::Blocks are full IDEs with integrated debuggers.
Terminal editors that run anywhere, including over SSH. Neovim has a built-in LSP client, so pairing it with clangd gives IDE features without leaving the terminal.
Popular free editor; install the C/C++ or clangd extension, then configure build tasks and launch.json to compile and debug with GDB or LLDB from the editor.
Write hello.c with #include <stdio.h> and a main that calls printf, compile with gcc -Wall -o hello hello.c, and run ./hello. Check echo $? to see the exit status.
A variable is a named object of a fixed type that occupies storage. C does not zero most variables for you, so where and how a variable is declared decides its initial value, lifetime and visibility.
A declaration introduces a name and type (extern int count;); a definition also allocates storage or provides a function body. A program may declare something many times but define it once.
Static and global objects start zeroed; automatic locals hold indeterminate garbage until assigned, and reading them is a classic bug. Use = {0} for aggregates and designated initializers like .x = 1.
printf needs a conversion specifier matching each argument's type: %d int, %ld long, %zu size_t, %f double, %c char, %s string, %p pointer. A mismatch is undefined behaviour, so compile with -Wformat.
C's built-in types are integers, characters, floating-point numbers and booleans, with sizes that depend on the platform — the standard only fixes minimum ranges. Use sizeof and <limits.h> rather than assuming, and <stdint.h> when width matters.
short, int, long and long long, each signed or unsigned. int is at least 16 bits (32 on mainstream platforms). Signed overflow is undefined behaviour; unsigned arithmetic wraps modulo 2ⁿ.
Single-precision floating point, nearly always IEEE 754 binary32 with about 7 significant decimal digits. Mostly used where memory or SIMD width matters; literals need an f suffix (1.5f).
The default floating type: IEEE binary64 with about 15–16 digits. Rounding means 0.1 + 0.2 != 0.3, so compare with a tolerance and never use floating point for money.
One byte, the unit sizeof counts in. Whether plain char is signed is implementation-defined, so use unsigned char for raw bytes and cast before passing to <ctype.h> functions.
C99 added _Bool and <stdbool.h> with bool, true and false; C23 makes them real keywords. Any scalar converts to bool as zero → false, anything else → true.
<stdint.h> provides int8_t … uint64_t for exact sizes, size_t for object sizes, intptr_t for pointers as integers, and <inttypes.h> macros such as PRIu64 for printing them.
long long, long double, _Complex numbers from <complex.h>, and in C23 bit-precise integers _BitInt(N). Support and exact precision vary by compiler and target, so check before relying on them.
Implicit integer promotions and the usual arithmetic conversions decide the type of mixed expressions — -1 < 0u is false because -1 becomes a huge unsigned. Casts are explicit conversions; enable -Wconversion to see silent narrowing.
Qualifiers add properties to a type without changing its representation: whether it may be modified, whether accesses may be optimised away, whether pointers may alias, and whether access is atomic. They matter most on pointers, where const char *p and char *const p mean different things.
Marks an object read-only through that name. Use it on pointer parameters (const char *s) to promise a function will not modify the caller's data; casting const away and writing is undefined behaviour.
Every read and write must actually happen, for memory-mapped hardware registers or variables changed by signal handlers. It does not make code thread-safe — use atomics for that.
A C99 promise that, for the pointer's lifetime, the object is only accessed through it. It lets the compiler vectorise and reorder loads, as with memcpy; breaking the promise is undefined behaviour.
C11 atomic types (and <stdatomic.h> operations like atomic_fetch_add) give data-race-free access between threads with chosen memory orderings. Not available on every implementation (__STDC_NO_ATOMICS__).
C has a dense set of operators with a precedence table worth keeping handy. Be aware of unsequenced side effects — i = i++ + 1 is undefined — and use parentheses whenever bitwise and comparison operators mix.
+ - * / % plus increment and decrement. Integer division truncates toward zero, % takes the sign of the dividend, and dividing by zero is undefined behaviour.
&&, || and ! produce int 0 or 1 and short-circuit: the right operand is not evaluated when the left decides the result, which makes p && p->next safe.
== != < > <= >= yield 1 or 0. Watch signed/unsigned mixes, never compare floats for exact equality, and remember = in a condition assigns — compilers warn with -Wall.
& | ^ ~ << >> manipulate bits for flags, masks and packing. Use unsigned types: shifting a negative value or by at least the type's width is undefined or implementation-defined.
cond ? a : b is an expression, so it works inside initializers and arguments. Keep it to simple choices; nested ternaries hurt readability fast.
Branches and loops: if/else, switch, for, while, do … while, plus break, continue, return and the occasionally useful goto. Any non-zero scalar counts as true in a condition.
switch jumps to a matching integer case and falls through to the next unless you break — C23 adds [[fallthrough]] to mark intentional cases. Always include a default.
for suits counted loops, while checks before each pass, do … while runs the body at least once. Watch off-by-one bounds and unsigned counters that never go below zero.
break leaves the innermost loop or switch; continue skips to the next iteration. To leave nested loops, use a flag, return from a helper function, or a goto to a label after them.
Functions take arguments by value — even arrays arrive as pointers — and return at most one value. Declare a prototype before use (usually in a header) so the compiler can check calls, and write (void) for an empty parameter list before C23.
The entry point: int main(void) or int main(int argc, char *argv[]). Its return value becomes the process exit status, and since C99 reaching the end of main returns 0.
argc counts arguments and argv holds them as strings, with argv[0] the program name and argv[argc] a null pointer. Parse options with POSIX getopt and numbers with strtol, checking errors.
A function may call itself, as in tree traversal or divide-and-conquer. Each call uses stack space and C does not guarantee tail-call elimination, so deep recursion can overflow the stack.
Block scope for locals, file scope for globals, plus function-prototype scope and labels. An inner name shadows an outer one, which -Wshadow flags.
Functions like printf take ... and read extra arguments with va_start, va_arg and va_end from <stdarg.h>. There is no type checking, and float and small integers are promoted to double and int.
A pointer holds the address of an object, and almost everything interesting in C — arrays, strings, dynamic data, output parameters, callbacks — goes through pointers. Understanding storage duration and lifetime is what keeps pointer code correct.
C sees memory as bytes holding objects, each with an address, size and alignment; C11 also defines how threads observe each other's writes. Data races on non-atomic objects are undefined behaviour.
Automatic locals usually live on the call stack — fast, limited in size and gone on return. Heap memory from malloc is larger and outlives the function but must be freed by you.
Automatic objects end with their block, static ones live for the whole program, allocated ones until free. Returning the address of a local is a classic bug: the pointer outlives the object.
int *p = &x; takes an address and *p dereferences it. Read declarations right to left, and use pointer parameters to let a function modify the caller's variables.
NULL (and C23's nullptr) is a pointer that points nowhere. Initialise pointers to it, check results from allocation and lookup functions, and never dereference it — that is undefined behaviour, usually a crash.
Adding n to a pointer moves it n elements, not bytes; subtracting two pointers into the same array gives a ptrdiff_t. Moving outside the array (other than one past the end) is undefined.
void * is C's generic pointer: any object pointer converts to and from it without a cast, which is how malloc, memcpy and qsort work with any type. You must convert it back before dereferencing.
C has no garbage collector: you request heap memory, track who owns it and release it exactly once. Most C security bugs come from getting this wrong, so pair every allocation with a clear owner and run sanitizers routinely.
Use the heap when a size is only known at run time or data must outlive the current function. Always check for NULL, compute sizes with sizeof *p, and guard multiplications against overflow.
malloc(n) returns n uninitialised bytes suitably aligned for any type, or NULL. In C there is no need to cast the result: int *a = malloc(count * sizeof *a);.
calloc(count, size) allocates an array and zeroes it. Good implementations also detect the count * size overflow that a hand-written malloc call can miss.
Resizes a block, possibly moving it. Assign the result to a temporary first — on failure it returns NULL and leaves the original allocated, so p = realloc(p, n) leaks.
Returns memory to the allocator. free(NULL) is a no-op, but freeing twice or freeing a pointer not from malloc is undefined; set the pointer to NULL afterwards to make reuse obvious.
Losing the last pointer to an allocation without freeing it. Short programs survive leaks; servers slowly grow until killed. Find them with LeakSanitizer or Valgrind and design clear ownership.
A pointer to memory that was freed or went out of scope. Using it (use-after-free) may appear to work, then corrupt data or become an exploit; ASan detects most cases.
Writing past an array's end, typically via strcpy, sprintf or an off-by-one loop. Prefer bounded functions such as snprintf, track lengths explicitly and fuzz input parsers.
Code the standard places no requirements on — out-of-bounds access, signed overflow, null dereference, data races. Optimisers assume it never happens, so it can silently delete checks; UBSan (-fsanitize=undefined) catches much of it.
Fixed-size sequences of elements stored contiguously. In most expressions an array decays to a pointer to its first element, so a function receiving one loses its length — pass the size separately, and note sizeof inside the function gives the pointer size. There is no bounds checking.
A C string is a char array terminated by a zero byte; the length is not stored, so strlen scans for it. Most string bugs are a missing terminator or a buffer too small. String literals are read-only, and <string.h> holds the copying, comparing and searching functions.
Structs, unions and enums let you model your own data, and typedef gives types short names. Layout matters in C: member order affects padding and size, and these types are often shared with hardware, files or other languages.
Group named members of different types. The compiler may add padding for alignment, so order members large to small; initialise with designated initializers and pass large structs by pointer.
All members share the same storage, so only one is meaningful at a time. Pair a union with a tag field for variant types; reading a different member than last written reinterprets the bytes, which C permits.
Named integer constants such as enum color { RED, GREEN };. They make switch statements readable and let -Wswitch warn about unhandled cases; C23 can fix the underlying type.
Creates an alias for an existing type, for example typedef struct node Node; or a function-pointer type. Useful for opaque handles; avoid hiding pointers behind typedefs where it confuses ownership.
The standard library has no containers, so C programmers build (or vendor) their own. Implementing a few by hand is the best exercise in pointers, allocation and ownership.
A struct holding a pointer, a length and a capacity; when full, grow the capacity geometrically (usually doubling) with realloc, giving amortised O(1) appends.
Nodes linked by pointers allow O(1) insertion and removal anywhere you hold a node, at the cost of poor cache locality. Intrusive lists, where the link lives inside your struct, avoid extra allocations.
A fixed array with head and tail indices that wrap around. With a power-of-two size the wrap is a cheap bitmask; a common choice for drivers, audio and producer-consumer queues.
Map keys to buckets with a hash function such as FNV-1a, resolving collisions by chaining or open addressing, and resize when the load factor grows. Average O(1) lookup.
Real C projects split into translation units: .c files with implementations and .h headers with the public interface. Linkage and the preprocessor decide what each file can see, and keeping internals static keeps modules decoupled.
Headers hold declarations, type definitions and macros shared between files — not definitions of variables or non-inline functions. Protect each with include guards or #pragma once.
External linkage makes a name visible across translation units, internal linkage keeps it inside one file, and locals have none. Two external definitions of one name cause a link error.
At file scope it gives internal linkage — the right default for helpers. Inside a function it makes a local keep its value between calls, which is handy but not thread-safe.
Declares a variable defined in another file (extern int verbose; in a header, one definition in a .c). Functions are extern by default.
Before compilation the preprocessor handles #include, #define and conditionals by text substitution. Inspect its output with gcc -E when macros misbehave.
Object-like and function-like #defines. Parenthesise parameters and the whole body, wrap statements in do { … } while (0), and beware arguments evaluated twice; prefer static inline functions when possible.
#if, #ifdef, #elif and #endif include code per platform, feature or build type, driven by -D flags. Keep these blocks small or they become untestable variants.
The compiler supplies __FILE__, __LINE__, __DATE__ and __STDC_VERSION__, plus platform macros such as __linux__ or _WIN32; __func__ gives the current function name. Useful for logging and portability checks.
C has no exceptions: functions signal failure through return values (-1, NULL, an error code) and sometimes errno. Check every call that can fail, propagate errors up explicitly and clean up on each path.
A thread-local integer that library calls set on failure. Only inspect it after a call reports an error, since success may leave it unchanged; turn it into text with strerror or perror.
Return EXIT_SUCCESS or EXIT_FAILURE from main or pass them to exit. On POSIX only the low 8 bits reach the parent shell, so keep custom codes between 1 and 125.
A non-local jump back to a saved point, sometimes used to emulate exceptions in parsers. It skips any cleanup, and locals changed after setjmp must be volatile to keep their values.
The standard library abstracts files and devices as buffered streams. Open, read or write, check every return value, and close — fclose can report errors too, such as a failed final flush.
stdin, stdout and stderr are open at startup. Output is buffered — line-buffered on terminals, fully buffered otherwise — so call fflush when order matters, or set buffering with setvbuf.
FILE *f = fopen(path, "r") returns a handle or NULL. Read with fgets or fread, write with fprintf or fwrite, move with fseek/ftell, and always fclose.
Adding b to the mode ("rb") disables newline translation. On POSIX the two modes behave the same, but on Windows text mode turns \n into \r\n, corrupting binary data.
A small set of headers covering I/O, strings, memory, math, time, character classes and signals. Many functions predate modern safety practice, so learn which ones to avoid (gets was removed, strcpy invites overflows).
<stdio.h>: formatted I/O with printf/scanf families, line input with fgets, and block I/O with fread/fwrite. Prefer snprintf and parse with strtol instead of trusting scanf.
<stdlib.h> covers allocation, conversions (strtol, strtod), qsort and bsearch, rand, and environment access with getenv. Avoid atoi, which cannot report errors.
<string.h> and <ctype.h>: strlen, strcmp, strchr, strstr, memcpy, memmove, and character tests like isdigit. Most assume valid null-terminated input, so track buffer sizes yourself.
<math.h> gives sqrt, pow, trigonometry and rounding (link with -lm on many systems); <time.h> gives time, clock, strftime and timespec_get. Use a monotonic clock for measuring durations.
<limits.h> and <float.h> expose ranges like INT_MAX and DBL_EPSILON; <assert.h> aborts on broken invariants during development. Check limits before arithmetic that might overflow.
<signal.h> installs handlers for events like SIGINT; <stdlib.h> offers exit, atexit and system. Signal handlers may only do async-signal-safe work, typically setting a volatile sig_atomic_t flag.
Turning source into a program happens in stages: preprocessing, compiling each file to an object file, then linking objects and libraries into an executable. Knowing the stages makes cryptic errors like "undefined reference" easy to place.
The compiler translates each translation unit to machine code, with flags choosing the standard (-std=c17), warnings and optimisation. GCC, Clang and MSVC dominate; embedded targets add vendor toolchains.
The two main open-source compilers, largely flag-compatible. A good default is -std=c17 -Wall -Wextra -Wpedantic -g, plus -fsanitize=address,undefined during development.
Fabrice Bellard's tiny, extremely fast C compiler; tcc -run file.c compiles and runs at once, handy for scripting-style use. It optimises little and lags on newer standards.
-O0 for debugging, -Og for debuggable optimised code, -O2 for release, -O3 for aggressive loop work and -Os for size. Higher levels expose latent undefined behaviour.
The linker resolves symbols between object files and libraries — static (.a, copied in) or shared (.so/.dylib/.dll, loaded at run time). With static libraries, order on the command line matters: -lfoo after the objects that use it.
Object files list the symbols they define and need. Inspect them with nm or readelf -s to debug undefined or duplicate symbols, and strip them from release binaries.
The binary contract: calling conventions, register use, struct layout and symbol names. A stable C ABI is why nearly every language can call C libraries, and why changing a public struct can break existing binaries.
Beyond a handful of files you need a tool that tracks dependencies and rebuilds only what changed. Make is the classic; CMake and Meson generate builds for many platforms and IDEs.
Rules of targets, prerequisites and tab-indented recipes, with pattern rules (%.o: %.c) and automatic variables like $@ and $<. Generate header dependencies with -MMD and build in parallel with -j.
The de facto cross-platform generator: describe targets with add_executable, add_library and target_link_libraries, then cmake -S . -B build && cmake --build build. Prefer target-based, modern CMake.
A minimal, very fast build executor meant to be generated by CMake (-G Ninja) or Meson rather than written by hand. It shines on incremental builds of large projects.
A build system with a readable, non-Turing-complete language that generates Ninja builds. Used by GNOME, systemd and many others; good defaults for warnings and sanitizers.
C has no official package manager. Linux distributions ship development packages (libcurl-dev) and pkg-config finds their flags; cross-platform projects use tools that fetch and build dependencies per project.
Microsoft's open-source C/C++ library manager. Declare dependencies in a vcpkg.json manifest and point CMake at its toolchain file; it builds libraries from source for your triplet.
A decentralised package manager written in Python, with recipes in a conanfile and prebuilt binaries per configuration. Integrates with CMake, Meson and others.
C bugs often show up far from their cause, so learn to use real tools: a debugger to stop and inspect, sanitizers to catch memory errors at the line they happen, and tracers to see what the program asks the OS to do. Compile with -g and low optimisation while debugging.
The GNU debugger: break, run, next, step, bt for a backtrace, print and watch for data. Load a core dump with gdb prog core to inspect a crash after the fact.
LLVM's debugger and the default on macOS. Commands differ from GDB but map closely (b, r, n, s, bt, p), and a GDB-to-LLDB command table eases the switch.
Microsoft's debugger for Windows user-mode and kernel code, especially for analysing crash dumps with symbol servers. Needed mostly for Windows-specific work.
Runs the unmodified binary on a synthetic CPU; its Memcheck tool reports invalid reads and writes, uninitialised values and leaks. Much slower than native and mainly for Linux.
AddressSanitizer (-fsanitize=address) instruments code to catch out-of-bounds and use-after-free with a precise report, at roughly 2x slowdown; LeakSanitizer reports leaks at exit. Run your tests under them.
Prints every system call a Linux process makes with arguments and results — ideal for "which file did it fail to open?". -f follows children, -e trace=open,read filters.
C has no built-in test runner, so projects use assertions plus a small framework. Keep functions small and pure where possible, build tests with sanitizers enabled and run them in CI on every change.
assert(expr) aborts with file and line when the condition is false; defining NDEBUG removes the checks, so never put side effects inside. static_assert checks conditions at compile time.
A tiny, portable framework from ThrowTheSwitch, popular for embedded C: a couple of source files, TEST_ASSERT_EQUAL-style macros and runners that work on microcontrollers.
A unit-testing framework that runs each test in a forked process, so a segfault fails one test instead of killing the whole suite. Organises tests into suites and cases.
A lightweight framework with built-in support for mock objects, typically wired up with the linker's --wrap option, plus checks for memory leaks and buffer issues in tests.
Without classes, templates or destructors, C programs rely on well-known idioms to get encapsulation, polymorphism and reliable cleanup. Reading mature codebases such as SQLite or the Linux kernel shows them in practice.
Declare typedef struct db db; in the header and define the struct only in the .c file. Callers hold pointers they cannot look inside, so you can change internals without breaking the API or ABI.
Structs with function-pointer tables act as vtables, embedding a base struct as the first member gives inheritance-like casting, and constructor/destructor functions manage lifetime.
The goto cleanup; pattern releases resources in reverse order from one exit path. GCC and Clang also offer __attribute__((cleanup(fn))) to run a function when a variable leaves scope.
Pointers to functions let you pass behaviour, as with qsort's comparator, event handlers or plugin tables. Typedef the signature, and pass a void * context so callbacks can carry state.
Threads share one address space, so shared data needs synchronisation or atomics — a data race is undefined behaviour. POSIX threads are the common API on Unix; C11 added an optional <threads.h> with similar primitives.
Create threads with pthread_create, wait with pthread_join, and compile with -pthread. Pass each thread a pointer to its own data and make sure that data outlives the thread.
pthread_mutex_lock/unlock guard critical sections; condition variables let threads wait for state changes. Always lock in a consistent order to avoid deadlocks, and keep critical sections short.
On POSIX systems a program creates processes with fork, replaces their image with the exec family and collects exit statuses with waitpid to avoid zombies. Shells, servers and supervisors are built from these few calls.
Ways separate processes exchange data: pipes and FIFOs for byte streams, POSIX shared memory (shm_open + mmap) for speed, message queues, Unix domain sockets and signals for notifications.
C is defined by ISO standards revised roughly once a decade. Pick one explicitly with -std=, and check __STDC_VERSION__ if code must support several; most new projects target C11 or C17, with C23 support arriving in recent compilers.
The first standard (ANSI 1989, adopted by ISO in 1990) introduced function prototypes, void *, const and the standard library. Still the baseline for ultra-portable code.
Added // comments, mixed declarations and code, <stdint.h>, <stdbool.h>, inline, restrict, designated initializers, compound literals, long long and variable-length arrays.
Brought a memory model, _Atomic and <threads.h>, _Generic, _Static_assert, _Alignas, anonymous structs and unions, and removed gets. VLAs became optional.
A bug-fix revision of C11 with no new features (__STDC_VERSION__ is 201710L). The usual default for compilers and a safe target today.
Adds bool/true/false and nullptr as keywords, typeof, constexpr objects, [[attributes]], #embed, binary literals, digit separators and _BitInt, and drops old K&R function definitions.