Skip to content
LumenaryAcademy
Foundations 50 min

First steps in C

Where C came from, why it is still everywhere, and how a source file becomes a running program.

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

Why learn C?

Some languages are popular because they are pleasant. C is everywhere because it is underneath. The Linux kernel is written in C, and so are large parts of Windows and macOS. So is the firmware in routers, cars, medical devices and washing machines. SQLite, probably the most widely deployed database in the world, is C; so are PostgreSQL and Redis. The standard interpreters of Python, Ruby, PHP and Lua are written in C, and when you pip install a fast numerical library, there is very likely C (or a language that speaks C's conventions) inside.

C also plays a quieter role: it is the lingua franca between languages. When Python calls a library written in Rust, or Go calls into an operating-system service, they almost always meet at a C-style interface, with C's types, C's calling convention and C's way of laying out data in memory. Knowing C means understanding that meeting point.

And C teaches you how computers really hold your data. There is no garbage collector, no bounds checking and no hidden copying. A variable is a few bytes at an address, an array is bytes in a row, and a string is bytes ending in a zero. That control is why C is fast and small, and also why C programs crash, leak and get hacked. A good C course has to teach both halves honestly, and this one will: by the end you will write C the way careful professionals do, with warnings, sanitizers, tests and build tools.

History & global context

From Bell Labs to C23

C was created by Dennis Ritchie at Bell Labs between 1969 and 1973, while he and Ken Thompson were building the Unix operating system. Thompson had written a small language called B, derived from Martin Richards's BCPL; B had no types, which suited the old machines it ran on but not the new PDP-11 with its bytes and words. Ritchie added types and structures, and by 1972 the new language had become C. In 1973 the Unix kernel itself was rewritten in C, an unusual choice at a time when operating systems were written in assembly, and it made Unix portable to new machines. That portability is how both spread.

In 1978 Brian Kernighan and Dennis Ritchie published The C Programming Language, the book everyone called "K&R" and which served as the language's definition for a decade. Then came formal standards:

StandardYearNotable additions
C89 / C90 (ANSI, then ISO)1989–1990the first standard: prototypes, void, the standard library
C991999// comments, stdint.h, bool, declarations anywhere, variable-length arrays
C112011threads and atomics, _Static_assert, _Generic, anonymous structs
C17 (also called C18)2018corrections only, no new features
C232024bool, true, false and nullptr as keywords, constexpr, typeof, #embed, attributes, checked integer arithmetic

This course teaches C17, the most widely supported complete standard, and points out C23 features where they help. Compiler support moves quickly: GCC 15 and later compile C as C23 by default (in its gnu23 dialect), and recent Clang versions support most of C23 with -std=c23. Our examples are checked with GCC 11 using -std=c17, the version on many long-term-support Linux systems, and the C23 snippets were checked with GCC 14.

C's design reflects its origin. Its committee has described the "spirit of C" with ideas such as trusting the programmer, keeping the language small and simple, and making it fast even at some cost in portability. In practice this means C does exactly what you write and checks very little for you. That is a trade-off, not a virtue in itself, and later lessons spend real time on its costs.

ComputationC

From source file to running program

Installing a compiler

You need a C compiler and a linker; on every system they come together:

  • Linux: sudo apt install build-essential (Debian, Ubuntu) or sudo dnf install gcc (Fedora) gives you GCC. sudo apt install clang adds Clang.
  • macOS: xcode-select --install installs Apple's Clang. The gcc command on a Mac is usually Clang under another name.
  • Windows: install the "Desktop development with C++" workload of Visual Studio (its compiler is cl, which also compiles C), or GCC through MSYS2, or use WSL and follow the Linux instructions.

Check with gcc --version or clang --version. To try things without installing anything, Compiler Explorer can compile and run C in the browser.

Hello, C

Save this as hello.c:

c
#include <stdio.h>

int main(void) {
    printf("Hello, C!\n");
    return 0;
}

Compile and run it:

bash
gcc -std=c17 -Wall -Wextra -o hello hello.c
./hello
text
Hello, C!

Line by line:

  • #include <stdio.h> pastes in the declarations of the standard input/output functions, including printf. Without it the compiler would not know what printf is.
  • int main(void) defines the function where every C program starts. int is the type of value it returns; (void) says it takes no arguments.
  • The body is between braces. Each statement ends with a semicolon.
  • printf("Hello, C!\n") prints the text. \n is an escape sequence for the newline character; C never adds one for you.
  • return 0; ends main and gives the operating system the exit status 0, which means success. (If main reaches its closing brace without a return, C also returns 0, but writing it is clearer.)

The command line matters too. -std=c17 asks for standard C17. -Wall -Wextra switch on a large set of warnings, messages about code that is legal but very likely wrong. -o hello names the output file. Always compile with warnings on; this course treats a warning as a bug until proven otherwise.

The four stages of a build

gcc runs four separate tools in a row. You can stop it after any of them:

StageWhat happensStop here with
Preprocessing#include files are pasted in and macros expandedgcc -E hello.c
CompilingC is translated to assembly for your processorgcc -S hello.c → hello.s
Assemblingassembly becomes machine code in an object filegcc -c hello.c → hello.o
Linkingobject files and libraries are combined into an executablegcc hello.o -o hello

It is worth looking at each once. On our machine, gcc -std=c17 -E hello.c produced 548 lines, nearly all of them declarations from stdio.h; your six lines are at the end. The object file hello.o contains machine code for main but not for printf: it only records that it needs a symbol called printf. The linker finds printf in the C standard library and connects the two. If you misspell printf as prinf, GCC 11 warns implicit declaration of function 'prinf'; did you mean 'printf'? (a compile-stage message), and then the link stage fails with undefined reference to `prinf'. (GCC 14 and later treat an implicit declaration as an error, in every language mode, which is better.) Knowing which stage an error comes from tells you where to look.

Worked examplesH

Printing with printf

printf takes a format string and then values to insert into it. Each % in the format starts a conversion specification that says how to print the next value:

SpecifierPrintsExample output
%dan int in decimal42
%fa double (6 decimals by default)3.140000
%.2fa double with 2 decimals3.14
%sa stringLima
%cone characterA
%zua size_t, the type of sizes8
%%a literal percent sign%

Between % and the letter you can add a width (pad to at least this many characters, on the left by default) and a precision after a dot. A - flag pads on the right instead, which left-aligns text in columns:

c
#include <stdio.h>

int main(void) {
    /* A small weather report: %s for text, %d for whole numbers,
       %.1f for a number with one digit after the decimal point. */
    printf("%-10s %6s %8s\n", "City", "Temp", "Rain mm");
    printf("%-10s %6.1f %8d\n", "Accra", 31.4, 12);
    printf("%-10s %6.1f %8d\n", "Oslo", -3.25, 0);
    printf("%-10s %6.1f %8d\n", "Lima", 19.0, 1);
    printf("%d%% of the cities are below freezing\n", 100 / 3);
    return 0;
}

It prints:

text
City         Temp  Rain mm
Accra        31.4       12
Oslo         -3.2        0
Lima         19.0        1
33% of the cities are below freezing

Two results deserve a second look. -3.25 printed as -3.2, not -3.3: −3.25 is exactly halfway between, and the GNU C library used here rounds such exact ties to the even digit. And 100 / 3 is 33, not 33.33: when both operands of / are integers, C performs integer division and throws the remainder away. The next lesson treats both properly.

Variables and a loop

You already know variables and loops from other languages; here they are in C. Every variable has a type that is fixed when it is declared, and the classic for loop has three parts: start, condition and step.

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

int main(void) {
    int savings = 1000;          /* in whole units of some currency */
    int rate_percent = 5;

    for (int year = 1; year <= 5; year++) {
        savings = savings + savings * rate_percent / 100;
        printf("after year %d: %d\n", year, savings);
    }
    return EXIT_SUCCESS;          /* the same as return 0 */
}

It prints:

text
after year 1: 1050
after year 2: 1102
after year 3: 1157
after year 4: 1214
after year 5: 1274

The fractions vanish each year (1102.5 became 1102) because savings is an int. Real financial code avoids both this truncation and floating-point rounding by storing amounts as whole numbers of the smallest unit, such as cents, and rounding deliberately. EXIT_SUCCESS, from stdlib.h, is a named constant for the success status; EXIT_FAILURE is its partner.

ExplanationH

How professionals compile

Experienced C programmers almost never type a bare gcc file.c. A typical development build looks like this:

bash
gcc -std=c17 -Wall -Wextra -Wpedantic -g -O0 -fsanitize=address,undefined -o app app.c
  • -Wpedantic warns about anything that is not standard C, which keeps code portable between compilers.
  • -g stores debugging information so that gdb or lldb can show source lines and variable names.
  • -O0 turns optimisation off for easy debugging; release builds use -O2.
  • -fsanitize=address,undefined adds run-time checks that catch out-of-bounds accesses, use of freed memory and many kinds of undefined behaviour. Lessons 7 and 9 show them at work.

Many teams also add -Werror in continuous integration, so that no warning can be merged, and run more than one compiler: GCC and Clang notice different problems. Project builds are driven by tools such as make and CMake rather than typed by hand, as the last lesson shows.

The warning flags are worth seeing in action. Here is a mistake that compiles, with the warning GCC 11 printed:

c
printf("%d\n", 3.5);    /* %d expects an int, but 3.5 is a double */
text
warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]

Without -Wall there is no warning at all, and the program prints a meaningless number.

Common misconceptionsH

Common misunderstandings

Misconception

"C is a subset of C++." They share ancestry and much syntax, but they are different languages with different standards committees. Some valid C is invalid C++ (for example, assigning a void * to an int * without a cast), and some code means different things in each. Learn C as C.

Misconception

"If it compiles, it is probably right." A C compiler accepts many programs that are badly wrong: wrong printf formats, reading past the end of an array, using a variable before giving it a value. Some of these produce warnings; some produce nothing. Warnings, sanitizers and tests are how professionals close that gap.

Misconception

"printf adds a newline." It prints exactly what you give it. Forgetting \n leaves the cursor on the same line, and because output is often buffered until a newline, text can appear late or, if the program crashes, not at all.

Misconception

"main must call exit to end." Returning from main ends the program and uses the return value as the exit status. exit() exists for ending the program from deep inside other functions.

Exercises

Exercises

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

1. First steps in C

Warm-upHuman

A build fails with the message undefined reference to `prinf'. Which stage of the build produced it?

Choose one

2. First steps in C

CoreComputational

What does printf("[%6.2f]\n", 3.14159); print? Type the whole line, brackets included, with its spaces.

3. First steps in C

Warm-upComputational

What does printf("%d\n", 7 / 2); print?

4. First steps in C

CoreComputational

In the savings program, rate_percent is changed to 10 and the loop runs for 3 years (year <= 3). What is the last line it prints?

5. First steps in C

Warm-upComputational

What does printf("%d%%\n", 50); print? (Without the newline.)

6. First steps in C

CoreHuman

Why does this course compile every program with -Wall -Wextra?

Choose one

7. First steps in C

Warm-upHuman

What was C originally created for?

Choose one

Further reading and resources