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 providesprintf.int main(void)is where every C program starts.intmeans it returns a whole number to the system;voidmeans it takes no arguments.- The braces
{ }hold the body ofmain. printfprints text.\nis 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);
| Placeholder | For |
|---|---|
%d | int |
%ld, %lld | long, long long |
%f | double (%.2f for two decimals) |
%c | a single char |
%s | a 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 youprintf.- Compile with
gcc -Wall file.c -o name, then run./name. printfplaceholders 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.