</>CodexBash
C
CBeginner9 min

Your first C program

What C is, the shape of every C program, compiling and running with gcc, printing with printf, and reading compiler errors.

C is one of the oldest languages still in everyday use, and one of the most important. Operating systems, databases, game engines and the runtimes of other languages are written in it. Learning C teaches you what the computer is actually doing, which makes every other language easier to understand.

Hello, world#

#include <stdio.h>

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

Every part of this is there for a reason:

  • #include <stdio.h> brings in the standard input and output library, which provides printf.
  • int main(void) is where every C program starts. int means it returns a whole number to the system; void means it takes no arguments.
  • The braces { } hold the body of main.
  • printf prints text. \n is a new line; without it the next output continues on the same line.
  • Every statement ends with a semicolon.
  • return 0; tells the system the program finished successfully.

Compiling and running#

C is a compiled language: a program called a compiler translates your source code into a file the machine can run directly. With gcc:

gcc hello.c -o hello
./hello

The first line compiles hello.c into a program named hello; the second runs it. On Windows the program is hello.exe.

Add warnings while learning. They catch real mistakes:

gcc -Wall -Wextra hello.c -o hello

Printing values#

printf takes a format string with placeholders, followed by the values to fill them:

int age = 21;
double price = 99.5;
printf("Age: %d\n", age);
printf("Price: %.2f\n", price);
printf("%d + %d = %d\n", 2, 3, 2 + 3);
PlaceholderFor
%dint
%ld, %lldlong, long long
%fdouble (%.2f for two decimals)
%ca single char
%sa string

The placeholder must match the type. printf("%d", 3.5) compiles but prints nonsense, which is exactly the kind of mistake -Wall warns about.

Comments#

// a comment to the end of the line

/* a comment that can
   span several lines */

Reading a compiler error#

hello.c:4:30: error: expected ';' before 'return'

That is file:line:column: message. Fix the first error and compile again. Later errors are often the compiler confused by the first one. The most common first errors are a missing semicolon, a missing closing brace, or a misspelled name.

Key points#

  • Every C program starts at main, and statements end with ;.
  • #include <stdio.h> gives you printf.
  • Compile with gcc -Wall file.c -o name, then run ./name.
  • printf placeholders must match the types of the values.
  • Fix compiler errors from the first one down.

Next: variables and C's types, where size really matters.

Create a free account to track your progress