Hello, world in C
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 0Learn
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, includingprintf. Without it, the compiler does not know whatprintfis.mainis where your program starts. Not the top of the file:main.printfprints text.\nis the newline character; C never adds one for you.return 0;hands an exit code back to whoever started the program.0means "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.
#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.
#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.
#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:
Now playing
Midnight Drive by Lumen
3:41 / 4:05On your own. Hints open after your first check.
Passed
You can now
Keep going