Lesson 3 of 7 · C Foundations · 3 min read · Updated

Your first C program

Write it, compile it, run it — and understand every line of it.

Here is the whole program. Type it out rather than copying it — typing it is part of learning it.

c
#include <stdio.h>

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

Every line, explained

Walk through it

  1. #include <stdio.h>

    This pulls in the standard input/output library, which is where printf lives. Without it the compiler has never heard of printf. The # marks it as an instruction to the preprocessor, which runs before compiling proper.

  2. int main(void)

    Every C program starts at main. The int says main hands back a whole number when it finishes; void says it takes no arguments. The operating system calls this function for you.

  3. The braces { }

    Everything between them is the body of main — the work it does. Braces group statements together everywhere in C, not just here.

  4. printf("Hello, world!\n");

    Prints the text. The \n is a newline — without it the next output would continue on the same line. The semicolon ends the statement, and C requires it.

  5. return 0;

    Hands 0 back to the operating system, which by convention means "finished without trouble". Any other number signals a problem.

Compiling and running it

A computer cannot run C directly. A compiler translates your C into machine code first. Save the file as hello.c, then from a terminal in that folder:

bash
gcc hello.c -o hello
./hello

Note

On Windows the second line is hello.exe rather than ./hello. If gcc is not found, install MinGW-w64 on Windows, build-essential on Ubuntu, or Xcode command line tools on a Mac.

Warning

Forgetting the semicolon is the most common first error. The compiler will often point at the next line, because that is where it noticed something was wrong — so check the line above the one it names.

What does return 0; at the end of main tell the system?

Try this now

  1. Change the message to your own name and compile again.
  2. Delete the \n and see what changes in the output.
  3. Delete a semicolon on purpose, and read what the compiler says. Getting familiar with error messages early saves hours later.

Create a free account to save your progress, or sign in.