Introduction & Setup

Introduction & Setup in C: Most modern languages are microwaves. You put in a frozen meal, press a button, and three minutes later food comes out.

The Analogy: Learning to Cook Without a Microwave

Most modern languages are microwaves. You put in a frozen meal, press a button, and three minutes later food comes out. You never touch the raw ingredients, and you never learn what heat actually does.

C hands you a knife, a pan, and a flame. There is no button for "make a list that grows by itself" and no button for "clean up the memory I finished with". You do those things yourself, in the order you choose, and the language does not check whether you got it right. What you gain is that nothing sits between your instructions and the processor executing them.

This is why C is still everywhere, fifty years on. The Linux kernel is C. Windows and macOS kernels are C. SQLite, Redis, Git, Nginx, Python's own interpreter, and the firmware in your microwave are all C. When a new language is created, it is very often written in C first.

The trade-off is blunt: C will let you write a program that reads memory it does not own, and it will compile without complaint. Learning C is largely learning to be careful on purpose.


Syntax or Core Structure

C was created in 1972 by Dennis Ritchie at Bell Labs, to rewrite the UNIX operating system in something more portable than assembly. Every C program starts from the same skeleton:

#include <stdio.h>

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

Output:

Hello, World!

Line by line:

  • #include <stdio.h> asks the preprocessor to paste in the standard input/output header, which is what makes printf a name the compiler recognises. Angle brackets mean "look in the system include path"; double quotes mean "look next to my source file first".
  • int main(void) is the entry point. Execution always begins at the first statement inside main, never at the top of the file. The void says explicitly that this program takes no arguments.
  • printf(...) writes formatted text to standard output.
  • \n is the newline escape. Without it, your next output continues on the same line, and many terminals will not show the line at all until a newline arrives.
  • return 0; hands an exit status back to the operating system. Zero means success; anything else means failure, which is how shell scripts and CI pipelines know whether your program worked.
// Two slashes start a comment that runs to the end of the line.
/* This style can span
   several lines. */

#include <stdio.h>

int main(void) {
    printf("Line one\n");
    printf("Line two, ");
    printf("still line two\n");
    return 0;
}

Output:

Line one
Line two, still line two

Notice that printf does not add a newline for you. That is a deliberate difference from Python's print, and it is the first sign that C does exactly what you say and nothing more.


Technical Depth: What "Compiled" Actually Means

C is compiled, and this single fact shapes everything else about the language.

gcc -std=c17 -Wall -Wextra -o hello hello.c   # translate to a binary
./hello                                        # run the binary

Your .c file is turned into machine code before it ever runs, in four distinct stages:

  1. Preprocessing — every #include is replaced by the entire text of that header, and every #define is substituted. The result is one enormous single file. You can see it with gcc -E hello.c.
  2. Compilation — that expanded text is checked and translated into assembly for your specific processor.
  3. Assembly — the assembly becomes an object file (hello.o): real machine bytes, but with unresolved references to things like printf.
  4. Linking — the object file is stitched together with the C standard library to produce a single executable that the operating system can load.

Two consequences matter immediately. First, misspelled names and type mistakes are caught before the program runs, so there is no C program that dies on line 400 because you typed prntf. Second, when the program does run, there is no interpreter, no virtual machine, and no garbage collector between your code and the CPU.

#include <stdio.h>

int main(void) {
    int x = 5;
    printf("%d\n", x)   // error: expected ';' before '}' token
    return 0;
}

The error message points at the line after the mistake, because the compiler only realises something is wrong when it reaches a token that cannot follow. Learning to look one line up is a genuine C skill.

Where the four stages can each fail

StageTypical errorWhat it looks like
Preprocessingheader not foundfatal error: stdio.h: No such file or directory
Compilationsyntax or type mistakeerror: expected ';' before ...
Compilationmissing declarationwarning: implicit declaration of function 'printf'
Linkingfunction never definedundefined reference to 'my_helper'
Linkinglibrary not passedundefined reference to 'sqrt' (needs -lm)

That last row catches almost every beginner. If you use sqrt from <math.h>, including the header is only half the job — the header promises the function exists, and -lm is what actually supplies it.

C versus the languages you probably know

CPythonJavaScript
Executioncompiled to machine codeinterpretedJIT compiled
Typingstatic, declared by youdynamicdynamic
Memoryyou allocate and free itgarbage collectedgarbage collected
Bounds checkingnone at allevery index checkedevery index checked
Entry pointint main(void)top of filetop of file
Errors foundmostly at compile timeat runtimeat runtime
Stringsarrays of bytes ending in \0first-class objectsfirst-class objects

The "no bounds checking" row is the one that surprises people most. Writing past the end of an array in C is not an error you catch — it is a corruption you discover later, somewhere else entirely.


Real World Example: A Complete First Program

#include <stdio.h>

int main(void) {
    char name[50];
    int birth_year = 0;

    printf("What is your name? ");
    if (scanf("%49s", name) != 1) {
        printf("Could not read a name.\n");
        return 1;
    }

    printf("What year were you born? ");
    if (scanf("%d", &birth_year) != 1) {
        printf("Could not read a year.\n");
        return 1;
    }

    const int current_year = 2026;
    int age = current_year - birth_year;

    printf("Hello, %s! You are about %d years old.\n", name, age);

    if (age >= 18) {
        printf("You can vote.\n");
    } else {
        printf("You have %d years to wait.\n", 18 - age);
    }

    return 0;
}

Output:

What is your name? Ada
What year were you born? 1990
Hello, Ada! You are about 36 years old.
You can vote.

Every line here is deliberate, and most of it is about distrust:

  • char name[50] reserves exactly fifty bytes. There is no growing string type in C; you decide the size up front and live with it.
  • "%49s" refuses to read more than 49 characters, leaving room for the terminating \0. Plain "%s" would happily write past the end of the array — one of the most exploited bugs in software history.
  • &birth_year passes the address of the variable, because scanf has to write into it. Forgetting the & on a numeric read is the single most common beginner crash in C.
  • Checking the return value of scanf matters: it returns how many items it successfully converted. If the user types "banana" for a year, birth_year is never assigned, and without the check you would compute an age from uninitialised memory.
  • int birth_year = 0; is initialised because an uninitialised local variable in C contains whatever bytes were previously on the stack. Reading it is undefined behaviour, not a zero.
  • return 1; on failure is what lets a caller — a shell script, a test harness — tell that something went wrong.

Common Mistakes

  1. Forgetting the semicolon. The reported error line is usually the line after the real problem.
  2. Omitting #include <stdio.h> and then using printf. Older compilers only warn about the implicit declaration, then generate subtly wrong code.
  3. Dropping the & in scanf("%d", x). This passes a value where an address is expected, and typically crashes immediately.
  4. Expecting printf to add a newline. It does not; your output will look like it vanished.
  5. Mismatching the format specifier and the argument, such as printf("%d", 3.14). The compiler warns with -Wall, and the runtime prints nonsense.
  6. Assuming return 0 is optional decoration. It is the program's exit status, and scripts act on it.
  7. Forgetting -lm when linking against <math.h>, then being baffled by an undefined reference that names a function you clearly included.
  8. Compiling with warnings switched off. In C, warnings are usually the compiler telling you exactly where your bug is.

Best Practices

  • Always compile with gcc -std=c17 -Wall -Wextra and treat every warning as an error to fix, not a note to ignore.
  • Write int main(void) rather than int main(), so the compiler knows you take no arguments.
  • Initialise every variable at the point you declare it.
  • Check the return value of anything that reads input or allocates memory.
  • Give arrays an explicit size and never let input decide how much you write.
  • Keep main short: read input, call functions, return a status.
  • Compile after every few lines. One error you understand beats ten you do not.
  • Read the first error message the compiler prints; the rest are often knock-on noise.

Practice Exercises

  1. Read the Error: Write and compile a program that prints your name, then delete one semicolon and note the exact line number the compiler reports. Explain why it is not the line you edited.
  2. The Interview: Extend the program above to also ask for a favourite language, then print one sentence combining the name, the age, and the language.
  3. Stage by Stage: Run gcc -E hello.c and count how many lines #include <stdio.h> expanded into. Then compile with gcc -c only, and confirm that no executable was produced.
  4. The Missing Library: Write a program that calls sqrt(2.0) with <math.h> included, compile it without -lm, read the linker error, then fix it. Describe which of the four stages failed.