CYour First C Program

Your First C Program

Every C programmer's first program prints "Hello, World!" to the screen. It's short enough to fully understand line by line, yet it touches every essential piece of a C program: including a library, defining main, calling a function, and returning a value.

The program

Create a file named hello.c with the following contents:

hello.c

C
#include <stdio.h>

int main(void) {
    printf("Hello, World!\n");
    return 0;
}
Line by line
  • #include <stdio.h> — pulls in declarations for the Standard Input/Output library, which is where printf comes from.

  • int main(void) — declares the main function, the entry point every C program must have. int means it returns a whole number; void means it takes no arguments.

  • { — opens the body of main; everything between this and the matching } is what runs when the program starts.

  • printf("Hello, World!\n"); — calls the printf function, passing it the text to display. \n is an escape sequence for a newline.

  • return 0; — ends main, handing the value 0 back to the operating system to signal that the program finished successfully.

  • } — closes the body of main.

Compiling and running it

Compile hello.c with GCC (or Clang):

Bash
gcc hello.c -o hello

This produces an executable named hello (or hello.exe on Windows). Run it:

Bash
./hello
# On Windows: hello.exe
Hello, World!

That's the entire cycle you'll repeat for every C program you write: edit the source file, compile it into an executable, then run that executable. The next few pages dig into exactly why each line is written the way it is.