C Foundations Lesson 1 of 7

Hello, world in C

20 min, 3 exercises

Learn

What a compiler does

A CPU does not understand C. It understands machine code: numbers that mean things like "add these two registers" or "jump to this address". A compiler is the program that translates your C source text into that machine code, once, before anything runs.

Here, your code is compiled by a real C compiler to WebAssembly, a machine code for a virtual CPU that your browser runs. On a laptop, gcc or clang would produce x86 or ARM machine code instead. Same idea, different target.

When the program runs, it sits in memory as bytes: the machine code for each function, plus your text. A string like "Hi!\n" is stored as one byte per character, each a small number, with a 0 byte added to mark the end:

 'H'  'i'  '!'  '\n'  end
  72  105   33   10     0

Learn

Shape of a C program

Every C program has the same skeleton:

#include <stdio.h>

int main(void) {
    printf("Hello!\n");
    return 0;
}
  • #include <stdio.h> pastes in the declarations for the standard input/output functions, including printf. Without it, the compiler does not know what printf is.
  • main is where your program starts. Not the top of the file: main.
  • printf prints text. \n is the newline character; C never adds one for you.
  • return 0; hands an exit code back to whoever started the program. 0 means "all good".
  • Every statement ends in ;. Forget one and the compiler will complain, loudly.

Compilers are strict. That is a feature: every error caught now is a bug you do not ship later. Read the error message. It usually points at the right line, or the one just after.

Try

Run it: a compiled greeting

The example is already in the editor. Run it, change one thing, and run it again.

example.c to run
#include <stdio.h>

int main(void) {
    printf("Hello from C!\n");
    printf("This text became machine code before it ran.\n");
    return 0;
}

Practice

Say hello

Print exactly Hello, C! followed by a newline.

exercise_1.c to run
#include <stdio.h>

int main(void) {
    // print the message here
    return 0;
}

Practice

Three lines

Print these three lines, exactly as shown, each on its own line:

  • I typed this.
  • I compiled this.
  • I understand this.

printf never starts a new line by itself, so each line needs its own \n at the end.

exercise_2.c to run
#include <stdio.h>

int main(void) {
    printf("I typed this.");
    return 0;
}

Your turn

Now-playing card

Write the whole program yourself this time, from #include to return 0;. It prints this card, with the empty line in the middle:

Output
Now playing
Midnight Drive by Lumen

3:41 / 4:05

On your own. Hints open after your first check.

exercise_3.c to run
C, 32-bit: int and pointers are 4 bytes

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.