thecodingidiot.com

f03d-why-c

Why C

The Scale Problem

The programs from the previous chapter — the counter, the button, the tone, the game loop — total about 200 bytes of assembly. Each line is an explicit instruction: load this register, store to this address, branch if this flag. Writing them requires tracking the full machine state in your head at all times: what is in the accumulator, what is in X, which flags the last instruction set, which zero-page addresses are in use.

200 bytes is manageable. 2 kilobytes is harder. 20 kilobytes is the point at which experienced assembly programmers begin to doubt themselves. Combat (1977) is 2KB. Adventure (1980) is 4KB. Space Invaders (1980) is around 4KB. These are programs where assembly remained tractable because the machine demanded it — the 2600's 128 bytes of RAM, the three-instruction-per-scanline TIA constraint, left no room for a compiler's overhead. The hardware was the constraint, not the programmer.

When the hardware got larger, the calculus changed.

The original Doom[1] (1993) is hundreds of kilobytes of compiled code. A small fraction of it — the innermost rendering loops — was hand-written assembly. The rest was C. Not because C was faster. Because maintaining that volume of assembly is not a tractable problem for a team on a deadline. The correctness cost alone would have slipped the ship date by years.

C exists because of that cost. Dennis Ritchie[2] designed it in 1972 at Bell Labs for Unix — a portable systems language that compiled to efficient machine code and let a programmer think in terms of functions and data structures rather than registers and flags.

Ken Thompson (left) and Dennis Ritchie (right), in 1973
Dennis Ritchie at Japan Prize Foundation ceremony in May 2011

The compiler's job was to translate; the programmer's job was to be correct. By the mid-1990s, every major console SDK was C-based: Sony's PS1 dev kit, Nintendo's tools for the N64, Sega's Saturn and Mega Drive development environments. The hardware had grown past the point where assembly was feasible as the primary language, and C filled the gap.

This chapter has no implementation pages. Read it and continue to f04 — the next chapter is where C programs begin, and understanding why C exists is what makes that chapter make sense.

Footnotes

  1. GitHub - id-Software/DOOM: DOOM Open Source Release

  2. Dennis Ritchie - Wikipedia

up next

Writing C

Writing C