Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

C From The Ground Up

The course has a new home: cfromthegroundup.com. It has the same lessons, plus progress tracking, search, and a “Try it online” button for most lessons. This book edition stays here as a mirror.

A progressive C learning workbook from basics to systems programming.

Each lesson is a small, readable program with the explanation in the comments and the code inline. The workbook is meant to stay close to the code that is actually here. This is not a polished application suite or portfolio showcase. It is a progression of lessons, exercises, and a few larger workbook-style projects.

How This Book Works

Every chapter follows the same pattern:

  1. A prose explanation of the concepts being taught
  2. The full, runnable C source file with detailed comments
  3. Compile-and-run instructions

The original .c files in the repository are the single source of truth. The comments are the lesson content. Read the chapter prose for the overview, then study the source to see it in action.

Structure

The book is organized into six progressive parts:

  • Part 1: The Beginner Path – Core language fundamentals from Hello World through strings
  • Part 2: The Intermediate Path – Pointers, structs, dynamic memory, file I/O, and command-line arguments
  • Part 3: The Advanced Path – Projects and deeper topics including function pointers, recursion, linked lists, bit manipulation, and a line-based text editor
  • Part 4: The Expert Path – Systems programming with sockets, process management, hash tables, and multithreading
  • Part 5: Expert Systems – Multi-file projects, external libraries, terminal UI with ncurses, data parsing, and a capstone text adventure
  • Part 6: The Toolsmith Path – Debugging with gdb and lldb, undefined behavior and the sanitizers, and testing in C

Quick Start

Most lessons are single-file programs. Pick one .c file, compile it, and run it:

cc -Wall -Wextra -std=c17 \
  "Part 1 - The Beginner Path_ Core Concepts/1_hello_world.c" \
  -o /tmp/1_hello_world

/tmp/1_hello_world

On Windows, take the course inside WSL (the Windows Subsystem for Linux), the supported way to run every lesson there. The site’s setup guide shows how to install a compiler on macOS, Linux and Windows.

Build Notes

  • The lessons teach C17 (-std=c17), which every current compiler accepts. CI compiles every lesson with -std=c17 and again with -std=c23, so the course also builds on the newest standard.
  • Most lessons compile with cc -Wall -Wextra -Wpedantic -Wstrict-prototypes -std=c17 lesson.c -o lesson_name.
  • Lessons 26 through 30 use POSIX APIs (sockets, fork, waitpid, pthread).
  • Lesson 30 needs -pthread.
  • Lesson 32 needs -lm.
  • Lessons 33 and 35 need -lncurses or -lncursesw, depending on your system.

Verification

The supported verification flow is:

make verify

That checks that every listing in this book matches its .c file, builds the book, and runs the smoke check under both Clang and GCC. GitHub Actions runs the same checks on every push and pull request.

License

This project is licensed under the MIT License.

Setting Up

Fifteen minutes, once. You will install a C compiler, get the lesson files and run your first program from a terminal. The same guide is on the site at https://cfromthegroundup.com/setup.

What You Need

  • A C compiler. Clang and GCC both work; on every system below the command is called cc.
  • A terminal, the text window where you type commands. Every lesson is compiled and run from one.
  • A text editor for reading and changing the code. Any editor works; VS Code is a good free choice.

Most lessons are portable C and run anywhere. Lessons 26, 29 and 30 use POSIX system calls and lessons 33 and 35 use the ncurses library, so those need macOS, Linux, or Linux inside Windows (WSL). The instructions below set all of that up.

macOS

Open Terminal (in Applications, Utilities) and install Apple’s command line tools. They include the Clang compiler, make and ncurses:

xcode-select --install

A window asks you to confirm the download. When it finishes, check that the compiler answers:

cc --version

On macOS, gcc is another name for Clang. That is fine: every lesson compiles with either.

Linux

Install the compiler, make, the ncurses headers and git (to get the lesson files) with your package manager.

Debian, Ubuntu and Linux Mint:

sudo apt update
sudo apt install build-essential libncurses-dev git

Fedora:

sudo dnf install gcc make ncurses-devel git

Arch Linux:

sudo pacman -S base-devel ncurses git

Then check that the compiler answers:

cc --version

Windows (WSL)

On Windows, take the course inside the Windows Subsystem for Linux: a real Ubuntu that runs next to Windows. This is the supported way to take the course on Windows, and every lesson works there, including the POSIX and ncurses ones. Open PowerShell as administrator and run:

wsl --install

Restart when asked, then open Ubuntu from the Start menu and choose a user name and password. From then on you are on Linux: follow the Debian and Ubuntu steps above.

Your Windows drives appear inside Ubuntu under /mnt/ (for example /mnt/c/Users/you), but keep the lessons in your Ubuntu home folder, where compiling is faster. VS Code with its WSL extension can edit files there directly.

Using the Terminal

A few commands are all you need:

  • pwd prints the folder you are in.
  • ls lists the files in it.
  • cd folder moves into a folder, and cd .. moves back up one.

Folder names with spaces must be quoted: cd "Part 1 - The Beginner Path_ Core Concepts". Press the Tab key to complete a name for you.

Get the Lesson Files

Every lesson on the site has a Download button on each source file. To get the whole course at once, clone the repository with git:

git clone https://github.com/dunamismax/c-from-the-ground-up.git
cd c-from-the-ground-up

The folder names contain spaces, so put quotes around them when you change into one:

cd "Part 1 - The Beginner Path_ Core Concepts"

Your First Program

In the folder that holds 1_hello_world.c, compile it, then run the program the compiler made:

cc -Wall -Wextra -std=c17 -o 1_hello_world 1_hello_world.c
./1_hello_world

If the terminal prints Hello, World!, you are ready. Head to Lesson 1: Hello, World! to learn what each line of that program does.

What the Flags Mean

  • cc runs the C compiler.
  • -Wall -Wextra turn on warnings. A warning is the compiler pointing at code that is legal but probably wrong. Read every one; the course’s own code compiles with none.
  • -std=c17 picks the version of the C language standard to follow. This course teaches C17, which every current compiler supports.
  • -o name names the program the compiler writes. Without it, you get a.out.
  • ./name runs a program from the current folder. The ./ is needed because the shell does not look for programs there by default.

Troubleshooting

  • cc: command not found: the compiler is not installed yet. Repeat the steps for your system above.
  • No such file or directory: you are not in the folder that holds the lesson file. Run ls to see what is there, and cd into the right folder.
  • undefined reference to `pthread_create` (or to sqrt): the lesson needs a library. Use the exact command in its “How to Compile and Run” section; it includes -pthread, -lm or -lncurses where needed.
  • cannot find -lncurses or ncurses.h: No such file: install the ncurses development package (libncurses-dev or ncurses-devel). Some systems call the library ncursesw: try -lncursesw.
  • The program waits and nothing happens: it is probably waiting for you to type something. Press Ctrl+C to stop any program.

Hello, World!

What you’ll learn: how a C program goes from source code to a running program, and what #include, main, printf and return do.

Before you start: Nothing. Install a compiler with the setup guide and you are ready.

Welcome to your first lesson in C! The journey to mastering C is challenging but incredibly rewarding. It all begins with this single step.

What Is a Compiler?

A COMPILER is a special program that translates the human-readable C code you write into the machine code that your computer can execute. The commands in this course call it cc, the usual name for your system’s C compiler: GCC (the GNU Compiler Collection) on most Linux systems, and Clang on macOS. Both work the same way for these lessons.

The Program, Line by Line

The whole program is only a few lines long. It starts with this one:

#include <stdio.h>

The #include is a PREPROCESSOR DIRECTIVE. It’s a command that runs before the main compilation process starts. It tells the compiler to find the file specified in the angle brackets < > and copy its entire content into the program at that spot.

We are including stdio.h, which stands for “Standard Input/Output Header”. This header file contains declarations for essential functions used for input and output operations, including the printf function we will use below.

Next comes the MAIN FUNCTION, which holds the rest of the program:

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

Every complete C program MUST have exactly one function named main. The execution of the program officially begins at the top of the main function. The curly braces { and } mark where the function’s BODY, its block of code, begins and ends.

Let’s break down its signature: int main(void)

  • int: This is the RETURN TYPE. It specifies that the main function will “return” an integer value to the operating system when it finishes. This integer is an “exit code” that signals whether the program ran successfully.

  • main: This is the required NAME for the starting function.

  • (void): This specifies the function’s PARAMETERS (the inputs it takes). void is a special keyword that means “nothing”. So, (void) tells us that this function takes no arguments or inputs.

printf() is a FUNCTION that “prints formatted” output to your console (the text window where you’ll run this program). This function is made available to us because we included <stdio.h>.

The text inside the double quotes, "Hello, World!\n", is a STRING LITERAL. This is the data we are passing as an argument to the printf function.

The \n at the end is a special “escape sequence” that represents a NEWLINE character. It tells the console to move the cursor to the next line after printing “Hello, World!”.

Finally, the semicolon ; at the end marks the end of a C STATEMENT. Most lines of executable code in C must end with a semicolon.

The return statement ends the execution of the main function. It sends a value back to the operating system. By convention, return 0; signals that the program executed successfully without any errors.

Full Source

/**
 * @file 1_hello_world.c
 * @brief Part 1, Lesson 1: Hello, World!
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file is your very first C program and lesson.
 * The lesson is taught through the comments in this file. Read them
 * from top to bottom to understand what's happening.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Welcome to your first lesson in C! The journey to mastering C is challenging
 * but incredibly rewarding. It all begins with this single step.
 *
 * WHAT IS A COMPILER?
 * A COMPILER is a special program that translates the human-readable C code you
 * write into the machine code that your computer can execute. This course calls
 * it `cc`, the name every Unix-like system gives its C compiler: on most Linux
 * systems that is GCC (the GNU Compiler Collection), and on macOS it is Clang.
 * Both compile every lesson the same way.
 */

// --- Part 1: Preprocessor Directives ---

/*
 * The `#include` is a PREPROCESSOR DIRECTIVE. It's a command that runs
 * *before* the main compilation process starts. It tells the compiler to find
 * the file specified in the angle brackets `< >` and copy its entire content
 * into this file right here.
 *
 * We are including `stdio.h`, which stands for "Standard Input/Output Header".
 * This header file contains declarations for essential functions used for
 * input and output operations, including the `printf` function we will use below.
 */
#include <stdio.h>

// --- Part 2: The Main Function ---

/*
 * This is the MAIN FUNCTION. Every complete C program MUST have exactly one
 * function named `main`. The execution of the program officially begins at the
 * top of the `main` function.
 *
 * Let's break down its signature: `int main(void)`
 *
 * - `int`: This is the RETURN TYPE. It specifies that the `main` function will
 *   "return" an integer value to the operating system when it finishes. This
 *   integer is an "exit code" that signals whether the program ran successfully.
 *
 * - `main`: This is the required NAME for the starting function.
 *
 * - `(void)`: This specifies the function's PARAMETERS (the inputs it takes).
 *   `void` is a special keyword that means "nothing". So, `(void)` tells us
 *   that this function takes no arguments or inputs.
 */
int main(void)
{ // The opening brace `{` marks the beginning of the function's code block (its body).

    // --- Part 3: Statements and Functions ---

    /*
     * `printf()` is a FUNCTION that "prints formatted" output to your console
     * (the text window where you'll run this program). This function is made
     * available to us because we included `<stdio.h>`.
     *
     * The text inside the double quotes, `"Hello, World!\n"`, is a STRING LITERAL.
     * This is the data we are passing as an argument to the `printf` function.
     *
     * The `\n` at the end is a special "escape sequence" that represents a NEWLINE
     * character. It tells the console to move the cursor to the next line after
     * printing "Hello, World!".
     *
     * Finally, the semicolon `;` at the end marks the end of a C STATEMENT.
     * Most lines of executable code in C must end with a semicolon.
     */
    printf("Hello, World!\n");

    /*
     * The `return` statement ends the execution of the `main` function. It sends
     * a value back to the operating system. By convention, `return 0;` signals
     * that the program executed successfully without any errors.
     */
    return 0;

} // The closing brace `}` marks the end of the function's body.

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Congratulations on writing your first C program!
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal. On Windows, use the Ubuntu terminal of WSL (the Windows
 *    Subsystem for Linux), which is how this course runs on Windows.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to translate this source code into an executable program.
 *    The command below does the following:
 *    - `cc`: Invokes the compiler (GCC or Clang, whichever your system has).
 *    - `-Wall -Wextra`: Enables all and extra warning flags to catch potential errors.
 *    - `-std=c17`: Asks for the C17 standard of the language. C has been revised
 *      several times (C89, C99, C11, C17, C23); C17 is supported by every current
 *      compiler, so it is the version this course teaches.
 *    - `-o 1_hello_world`: Specifies the output file name should be `1_hello_world`.
 *    - `1_hello_world.c`: Specifies the input source file to compile.
 *
 *    `cc -Wall -Wextra -std=c17 -o 1_hello_world 1_hello_world.c`
 *
 * 4. Run the newly created executable:
 *    - On Linux/macOS:   `./1_hello_world`
 *    - On Windows (WSL): `./1_hello_world`
 *
 * You should see "Hello, World!" printed to your console.
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 1_hello_world 1_hello_world.c
./1_hello_world

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Change the message to greet yourself by name, then compile and run it again.
  2. Print three lines with three printf calls, then print the same three lines with one printf that contains three \ns.
  3. Delete the semicolon after the printf call and compile. Read the error message: which line does it point at? Put the semicolon back.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/01-hello-world/ in the repository and on this lesson’s page on the website.

Variables and Data Types

What you’ll learn: variables, the int, double and char types, and printing values with format specifiers such as %d, %.2f and %c.

Before you start: Lesson 1.

In the last lesson, we printed a fixed message. To write useful programs, we need a way to store and manipulate data that can change. This is where variables come in.

What Is a Variable?

A VARIABLE is a named storage location in the computer’s memory. Think of it as a labeled box where you can store a piece of information. You give it a name, and you can change the contents of the box (the value) as your program runs.

What Is a Data Type?

A DATA TYPE specifies the type of data that a variable can hold. C is a “statically-typed” language, which means you must explicitly tell the compiler the data type of every variable you create. This helps the compiler allocate the correct amount of memory and ensures you use the variable correctly.

The process of creating a variable is called DECLARATION. The process of giving a variable its first value is called INITIALIZATION.

An INTEGER is a whole number (no decimal point). The int data type is used to store them.

The lesson first DECLARES a variable named player_score of type int:

int player_score;

This tells the compiler: “Reserve a spot in memory for an integer, and I will call it player_score.”

Then it INITIALIZES the variable by assigning it a value using the assignment operator =:

player_score = 1250;

You can also declare and initialize a variable in one step, which is what you will usually do:

int number_of_lives = 3;

To print the value of a variable, we use printf with a FORMAT SPECIFIER. A FORMAT SPECIFIER is a placeholder in the string that tells printf what type of data to expect and how to format it.

printf("Player score: %d\n", player_score);

%d is the format specifier for a signed decimal integer (int). The variable player_score is passed as a second argument to printf, and its value will replace %d in the output.

To store numbers with decimal points, we use FLOATING-POINT types. The most common one is double, which stands for “double-precision”. It can store numbers with much greater precision than its counterpart, float. For this course, we will prefer double for all decimal numbers.

double item_price = 19.99;

%f is the format specifier for a double (and float).

By default, %f might print many extra zeros. You can control the number of decimal places by modifying the format specifier. For example, %.2f tells printf to print only 2 digits after the decimal point:

printf("The price, formatted neatly, is: $%.2f\n", item_price);

(The $ here is just a character in the message; only the % starts a format specifier.)

The char data type is used to store a single CHARACTER. This can be a letter, a number, or a symbol.

A CHARACTER LITERAL is enclosed in SINGLE quotes (e.g., ‘A’). This is different from a string literal, which uses double quotes.

char player_grade = 'A';

%c is the format specifier for a char.

You can print multiple variables in a single printf call. Just make sure the format specifiers and the variables are listed in the same order:

printf("Summary: Player with %d lives and a grade of '%c' has a score of %d.\n",
       number_of_lives, player_grade, player_score);

The first %d gets number_of_lives, the %c gets player_grade and the second %d gets player_score.

Full Source

/**
 * @file 2_variables_and_data_types.c
 * @brief Part 1, Lesson 2: Variables and Data Types
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file introduces the fundamental concepts of variables and data types.
 * We learn how to store information in memory and print it to the console.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * In the last lesson, we printed a fixed message. To write useful programs,
 * we need a way to store and manipulate data that can change. This is where
 * variables come in.
 *
 * WHAT IS A VARIABLE?
 * A VARIABLE is a named storage location in the computer's memory. Think of it
 * as a labeled box where you can store a piece of information. You give it a
 * name, and you can change the contents of the box (the value) as your
 * program runs.
 *
 * WHAT IS A DATA TYPE?
 * A DATA TYPE specifies the type of data that a variable can hold. C is a
 * "statically-typed" language, which means you must explicitly tell the
 * compiler the data type of every variable you create. This helps the compiler
 * allocate the correct amount of memory and ensures you use the variable correctly.
 *
 * The process of creating a variable is called DECLARATION.
 * The process of giving a variable its first value is called INITIALIZATION.
 */

#include <stdio.h>

int main(void)
{
    // The main function body is where we'll declare and use our variables.

    // --- Part 1: The Integer (int) ---

    /*
     * An INTEGER is a whole number (no decimal point). The `int` data type is
     * used to store them.
     *
     * Below, we DECLARE a variable named `player_score` of type `int`.
     * This tells the compiler: "Reserve a spot in memory for an integer,
     * and I will call it `player_score`."
     */
    int player_score; // Declaration

    /*
     * Now we INITIALIZE the variable by assigning it a value using the
     * assignment operator `=`.
     */
    player_score = 1250; // Initialization

    /*
     * To print the value of a variable, we use `printf` with a FORMAT SPECIFIER.
     * A FORMAT SPECIFIER is a placeholder in the string that tells `printf`
     * what type of data to expect and how to format it.
     *
     * `%d` is the format specifier for a signed decimal integer (`int`).
     * The variable `player_score` is passed as a second argument to `printf`,
     * and its value will replace `%d` in the output.
     */
    printf("Player score: %d\n", player_score);

    // You can also declare and initialize a variable in a single statement.
    int number_of_lives = 3;
    printf("Number of lives: %d\n", number_of_lives);
    printf("\n"); // Print a blank line for separation

    // --- Part 2: The Double-Precision Floating-Point Number (double) ---

    /*
     * To store numbers with decimal points, we use FLOATING-POINT types.
     * The most common one is `double`, which stands for "double-precision".
     * It can store numbers with much greater precision than its counterpart, `float`.
     * For this course, we will prefer `double` for all decimal numbers.
     *
     * `%f` is the format specifier for a `double` (and `float`).
     */
    double item_price = 19.99; // Declaration and initialization
    printf("The price of the magic sword is: $%f\n", item_price);

    /*
     * By default, `%f` might print many extra zeros. You can control the
     * number of decimal places by modifying the format specifier. For example,
     * `%.2f` tells `printf` to print only 2 digits after the decimal point.
     */
    printf("The price, formatted neatly, is: $%.2f\n", item_price);
    printf("\n");

    // --- Part 3: The Character (char) ---

    /*
     * The `char` data type is used to store a single CHARACTER. This can be
     * a letter, a number, or a symbol.
     *
     * A CHARACTER LITERAL is enclosed in SINGLE quotes (e.g., 'A'). This is
     * different from a string literal, which uses double quotes.
     *
     * `%c` is the format specifier for a `char`.
     */
    char player_grade = 'A'; // Declaration and initialization
    printf("Player's performance grade: %c\n", player_grade);

    // --- Part 4: Putting It All Together ---

    /*
     * You can print multiple variables in a single `printf` call. Just make
     * sure the format specifiers and the variables are listed in the same order.
     */
    printf("Summary: Player with %d lives and a grade of '%c' has a score of %d.\n",
           number_of_lives, player_grade, player_score);

    return 0; // Signal successful execution
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * In this lesson, you learned about three fundamental data types:
 * - `int` for whole numbers.
 * - `double` for numbers with decimal points.
 * - `char` for single characters.
 *
 * You also learned how to DECLARE variables, INITIALIZE them with values, and
 * print them using `printf` with FORMAT SPECIFIERS (`%d`, `%f`, `%c`).
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 2_variables_and_data_types 2_variables_and_data_types.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./2_variables_and_data_types`
 *    - On Windows (WSL): `./2_variables_and_data_types`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 2_variables_and_data_types 2_variables_and_data_types.c
./2_variables_and_data_types

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Add a double variable for the player’s health, set it to 87.5, and print it with one decimal place.
  2. Print item_price with %.0f, %.1f and %.3f. What does the number after the dot control?
  3. Print a char variable with %d instead of %c. The number you see is the character’s code.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/02-variables-and-data-types/ in the repository and on this lesson’s page on the website.

User Input

What you’ll learn: reading numbers and characters from the keyboard with scanf, why it needs &, and how to check that it worked.

Before you start: Lessons 1 and 2.

So far, our programs have been one-way streets: they run and print things without any input from the outside world. To build truly useful tools, we need our programs to be interactive.

The scanf Function

The counterpart to printf (for printing) is scanf (for scanning/reading). The scanf function reads formatted input from the standard input, which is usually your keyboard.

Like printf, it uses FORMAT SPECIFIERS to know what type of data to expect. However, it has one very important new requirement we will explore.

To read input, we first need a variable to store that input in. We DECLARE an integer variable user_age and INITIALIZE it to 0. The user will provide the real value, but if reading fails, the variable still holds a known value instead of leftover garbage from memory.

int user_age = 0;

It’s good practice to print a “prompt” to the user, so they know what you’re asking for:

printf("Please enter your age (as a whole number): ");

Now, we call scanf. This is the most important part of the lesson:

scanf("%d", &user_age)
  • "%d": This is the format specifier. It tells scanf to look for and read an integer from the keyboard input.

  • &user_age: This is new! The & symbol is the ADDRESS-OF OPERATOR. It gets the memory address of the user_age variable.

Why Do We Need &?

You must tell scanf where in memory to store the data it reads. Simply providing user_age would only give scanf the variable’s current value (which is just 0 at this point). By providing &user_age, you are giving it the location of the box, so it can put the user’s input directly into it.

Checking That scanf Worked

Users do not always type what you ask for. What if they type abc instead of a number? Then scanf cannot read an integer, and user_age is left unchanged.

Luckily, scanf tells us how it went. It RETURNS the NUMBER OF ITEMS it successfully read and stored:

  • 1 means it read our one integer. Success!
  • 0 means the input did not match %d (for example, abc).
  • EOF (a special negative value from <stdio.h>) means there was no input left at all. You can cause this by pressing Ctrl+D (Linux/macOS) or Ctrl+Z then Enter (Windows) instead of typing a number.

So we compare the result to 1:

if (scanf("%d", &user_age) != 1)
{
    printf("Could not read a whole number. Exiting.\n");
    return 1;
}

This means: “if scanf did NOT read exactly 1 item, print a message and stop the program.” You will learn exactly how if and != work in Lessons 4 and 5. For now, recognize the pattern, because you should use it every time you call scanf. return 1; ends main early with an exit code that signals an error.

Reading Other Types

The pattern is the same for other data types. We just need to change the variable type and the format specifier:

double user_gpa = 0.0;
printf("Please enter your GPA (e.g., 3.8): ");
if (scanf("%lf", &user_gpa) != 1)
{
    printf("Could not read a number. Exiting.\n");
    return 1;
}
printf("Your GPA is %.2f.\n", user_gpa);

IMPORTANT: For scanf, the format specifier for a double is %lf (which stands for “long float”). This is DIFFERENT from printf, which uses %f for a double. This is a common point of confusion!

The Leftover Newline

scanf can sometimes behave in unexpected ways because of how it handles whitespace (like spaces, tabs, and newlines).

When you typed your GPA and pressed Enter, the \n (newline character) was left behind in the INPUT BUFFER. A subsequent scanf call for a character (%c) would read that leftover newline instead of waiting for you to type a new character!

THE FIX: To fix this, we put a single space before the %c in the format string: " %c". That leading space tells scanf to “skip any and all leading whitespace characters before reading the character”. It’s a crucial trick:

if (scanf(" %c", &favorite_letter) != 1)

Full Source

/**
 * @file 3_user_input.c
 * @brief Part 1, Lesson 3: User Input
 * @author dunamismax
 * @date 06-15-2025
 *
 * This lesson demonstrates how to make programs interactive by reading
 * input from the user's keyboard.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * So far, our programs have been one-way streets: they run and print things
 * without any input from the outside world. To build truly useful tools,
 * we need our programs to be interactive.
 *
 * THE `scanf` FUNCTION
 * The counterpart to `printf` (for printing) is `scanf` (for scanning/reading).
 * The `scanf` function reads formatted input from the standard input, which is
 * usually your keyboard.
 *
 * Like `printf`, it uses FORMAT SPECIFIERS to know what type of data to expect.
 * However, it has one very important new requirement we will explore.
 */

#include <stdio.h>

int main(void)
{
    // --- Part 1: Reading an Integer ---

    /*
     * To read input, we first need a variable to store that input in.
     * We DECLARE an integer variable `user_age` and INITIALIZE it to 0. The user
     * will provide the real value, but if reading fails, the variable still
     * holds a known value instead of leftover garbage from memory.
     */
    int user_age = 0;

    /*
     * It's good practice to print a "prompt" to the user, so they know
     * what you're asking for.
     */
    printf("Please enter your age (as a whole number): ");

    /*
     * Now, we call `scanf`. This is the most important part of the lesson.
     *
     * - `"%d"`: This is the format specifier. It tells `scanf` to look for
     *   and read an integer from the keyboard input.
     *
     * - `&user_age`: This is new! The `&` symbol is the ADDRESS-OF OPERATOR.
     *   It gets the memory address of the `user_age` variable.
     *
     * WHY DO WE NEED `&`?
     * You must tell `scanf` *where* in memory to store the data it reads.
     * Simply providing `user_age` would only give `scanf` the variable's
     * *current value* (which is just 0 at this point). By providing `&user_age`,
     * you are giving it the *location* of the box, so it can put the user's
     * input directly into it.
     *
     * CHECKING THAT `scanf` WORKED
     * Users do not always type what you ask for. What if they type `abc`
     * instead of a number? Then `scanf` cannot read an integer, and `user_age`
     * is left unchanged.
     *
     * Luckily, `scanf` tells us how it went. Like many functions, it RETURNS a
     * value: the NUMBER OF ITEMS it successfully read and stored.
     * - `1` means it read our one integer. Success!
     * - `0` means the input did not match `%d` (for example, `abc`).
     * - `EOF` (a special negative value from <stdio.h>) means there was no input
     *   left at all. You can cause this by pressing Ctrl+D (Linux/macOS) or
     *   Ctrl+Z then Enter (Windows) instead of typing a number.
     *
     * So we compare the result to 1. The `if` statement below means: "if `scanf`
     * did NOT read exactly 1 item, print a message and stop the program." You
     * will learn exactly how `if` and `!=` ("not equal to") work in Lessons 4
     * and 5. For now, recognize the pattern, because you should use it every
     * time you call `scanf`.
     *
     * `return 1;` ends `main` early. Remember from Lesson 1 that returning 0
     * means success, so returning 1 tells the operating system something went
     * wrong.
     */
    if (scanf("%d", &user_age) != 1)
    {
        printf("Could not read a whole number. Exiting.\n");
        return 1;
    }

    // Let's print the value to confirm we received it correctly.
    printf("Thank you. You entered %d.\n", user_age);
    printf("\n"); // Add a blank line for spacing.

    // --- Part 2: Reading a Double ---

    /*
     * The pattern is the same for other data types. We just need to change
     * the variable type and the format specifier.
     *
     * IMPORTANT: For `scanf`, the format specifier for a `double` is `%lf`
     * (which stands for "long float"). This is DIFFERENT from `printf`,
     * which uses `%f` for a `double`. This is a common point of confusion!
     */
    double user_gpa = 0.0;
    printf("Please enter your GPA (e.g., 3.8): ");
    if (scanf("%lf", &user_gpa) != 1) // Use %lf for reading a double!
    {
        printf("Could not read a number. Exiting.\n");
        return 1;
    }

    printf("Your GPA is %.2f.\n", user_gpa); // Use %f for printing a double.
    printf("\n");

    // --- Part 3: A Common `scanf` Pitfall and Reading a Character ---

    /*
     * `scanf` can sometimes behave in unexpected ways because of how it handles
     * whitespace (like spaces, tabs, and newlines).
     *
     * When you typed your GPA and pressed Enter, the `\n` (newline character)
     * was left behind in the INPUT BUFFER. A subsequent `scanf` call for a
     * character (`%c`) would read that leftover newline instead of waiting for
     * you to type a new character!
     *
     * THE FIX: To fix this, we put a single space before the `%c` in the format
     * string: `" %c"`. That leading space tells `scanf` to "skip any and all
     * leading whitespace characters before reading the character". It's a crucial trick.
     */
    char favorite_letter = '?';
    printf("Please enter your favorite letter: ");
    if (scanf(" %c", &favorite_letter) != 1) // The space before %c is very important!
    {
        printf("Could not read a letter. Exiting.\n");
        return 1;
    }

    printf("Your favorite letter is '%c'.\n", favorite_letter);

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * In this lesson, you learned the basics of making your programs interactive.
 *
 * Key Takeaways:
 * - The `scanf()` function reads formatted input from the keyboard.
 * - `scanf()` requires the ADDRESS-OF OPERATOR `&` before the variable name to know
 *   *where* to store the input.
 * - Format specifiers for `scanf()` can sometimes be different from `printf()`.
 *   - For `double`: Use `%lf` with `scanf`, but `%f` with `printf`.
 * - `scanf()` can leave newline characters in the input buffer, which can cause
 *   problems. The `" %c"` trick (with a leading space) is used to solve this
 *    when reading characters.
 * - `scanf()` RETURNS the number of items it successfully read. Always check it:
 *   `if (scanf("%d", &x) != 1)` catches both bad input (`0`) and no input
 *   (`EOF`). Never use a variable that `scanf` failed to fill.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 3_user_input 3_user_input.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./3_user_input`
 *    - On Windows (WSL): `./3_user_input`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 3_user_input 3_user_input.c
./3_user_input

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Ask for the user’s birth year and print how old they turn this year.
  2. Run the program and type abc at the first prompt, then run it again and press Ctrl+D. Which message do you get each time, and why?
  3. Remove the space in " %c" and run the program again. What happens at the letter prompt?

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/03-user-input/ in the repository and on this lesson’s page on the website.

Basic Operators

What you’ll learn: arithmetic, relational and logical operators, integer division, the modulus operator and operator precedence.

Before you start: Lessons 1-3.

In programming, an OPERATOR is a special symbol that performs an operation on one or more values or variables (called OPERANDS). For example, in 5 + 3, the + is the operator and 5 and 3 are the operands.

We will explore three main categories of operators in this lesson:

  1. Arithmetic Operators: For performing mathematical calculations.
  2. Relational Operators: For comparing two values.
  3. Logical Operators: For combining multiple comparisons.

Arithmetic Operators

The lesson works with two integers:

int a = 10;
int b = 3;

+ (addition), - (subtraction) and * (multiplication) work just as they do in math: a + b is 13, a - b is 7 and a * b is 30.

/ (Division)

This one is tricky! When you divide two integers in C, the result is also an integer. The fractional part is simply thrown away (truncated). This is called INTEGER DIVISION. So a / b is 3, not 3.333.

To get a precise decimal result, at least one of the operands must be a floating-point type (like double). We can achieve this by “casting” one of the integers to a double:

double precise_division = (double)a / b;

Now precise_division holds 3.333333.

% (Modulus)

This operator gives you the REMAINDER of an integer division. a % b is 1, because 10 divided by 3 is 3 with 1 left over. It is incredibly useful: for example, n % 2 is 0 exactly when n is even. (To print a % sign with printf, write %%, because a single % starts a format specifier.)

Relational Operators

RELATIONAL OPERATORS are used to compare two values. The result of a relational operation is a “truth” value, and in C that value is an int:

  • 0 represents FALSE.
  • Any non-zero integer represents TRUE. Comparisons always give 1.

The six relational operators are == (equal to; note the TWO equals signs), != (not equal to), >, <, >= and <=. With a as 10 and b as 3, a == 10 is 1 and a == b is 0.

(Modern C does have a boolean type, bool, with the values true and false. You will meet it in a later lesson. Even so, comparisons and logical operators still produce the int values 1 and 0.)

Logical Operators

LOGICAL OPERATORS are used to combine or modify logical (true/false) expressions:

  • && (AND) is true only if BOTH sides are true.
  • || (OR) is true if AT LEAST ONE side is true.
  • ! (NOT) flips a value: !0 is 1, and !1 is 0.
int is_player_alive = 1; // 1 for true
int has_key = 0;         // 0 for false

Here is_player_alive && has_key is 0 (the player cannot open the door), is_player_alive || has_key is 1, and !has_key is 1.

Operator Precedence

Just like in math (PEMDAS/BODMAS), operators in C have a default order of evaluation called OPERATOR PRECEDENCE. For example, * and / are evaluated before + and -, so 5 + 2 * 10 is 25, not 70.

You can use parentheses () to force a specific order of evaluation, just like in math: (5 + 2) * 10 is 70. It’s often a good idea to use parentheses to make your code clearer, even when not strictly necessary.

Full Source

/**
 * @file 4_basic_operators.c
 * @brief Part 1, Lesson 4: Basic Operators
 * @author dunamismax
 * @date 06-15-2025
 *
 * This lesson covers the fundamental operators in C used for performing
 * calculations and making comparisons.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * In programming, an OPERATOR is a special symbol that performs an operation on
 * one or more values or variables (called OPERANDS). For example, in `5 + 3`,
 * the `+` is the operator and `5` and `3` are the operands.
 *
 * We will explore three main categories of operators in this lesson:
 * 1. Arithmetic Operators: For performing mathematical calculations.
 * 2. Relational Operators: For comparing two values.
 * 3. Logical Operators: For combining multiple comparisons.
 */

#include <stdio.h>

int main(void)
{
    // Let's declare some variables to work with.
    int a = 10;
    int b = 3;

    // --- Part 1: Arithmetic Operators ---

    printf("--- Part 1: Arithmetic Operators ---\n");
    printf("Initial values: a = %d, b = %d\n\n", a, b);

    // `+` (Addition)
    printf("a + b = %d\n", a + b);

    // `-` (Subtraction)
    printf("a - b = %d\n", a - b);

    // `*` (Multiplication)
    printf("a * b = %d\n", a * b);

    /*
     * `/` (Division) - This one is tricky!
     * When you divide two integers in C, the result is also an integer.
     * The fractional part is simply thrown away (truncated). This is called
     * INTEGER DIVISION.
     */
    printf("Integer Division (a / b) = %d\n", a / b); // 10 / 3 is 3, not 3.333

    /*
     * To get a precise decimal result, at least one of the operands must be a
     * floating-point type (like `double`). We can achieve this by "casting"
     * one of the integers to a double.
     */
    double precise_division = (double)a / b;
    printf("Floating-Point Division ((double)a / b) = %f\n", precise_division);

    /*
     * `%` (Modulus)
     * This operator gives you the REMAINDER of an integer division. It is
     * incredibly useful in many programming scenarios.
     */
    printf("Modulus (a %% b) = %d\n", a % b); // 10 divided by 3 is 3 with a remainder of 1.
    // Note: To print a literal '%' character in printf, you must type '%%'.
    printf("\n");

    // --- Part 2: Relational Operators ---

    /*
     * RELATIONAL OPERATORS are used to compare two values. The result of a
     * relational operation is a "truth" value, and in C that value is an `int`:
     * - `0` represents FALSE.
     * - Any non-zero integer represents TRUE. Comparisons always give `1`.
     *
     * (Modern C does have a boolean type, `bool`, with the values `true` and
     * `false`. You will meet it in a later lesson. Even so, comparisons and
     * logical operators still produce the `int` values 1 and 0.)
     */
    printf("--- Part 2: Relational Operators ---\n");
    printf("The results below will be 1 for TRUE and 0 for FALSE.\n\n");

    // `==` (Equal to) - VERY IMPORTANT:
    // A single `=` is for assignment. A double `==` is for comparison.
    // This is one of the most common beginner mistakes!
    printf("Is a == 10? %d\n", a == 10); // True (1)
    printf("Is a == b?  %d\n", a == b);  // False (0)

    // `!=` (Not equal to)
    printf("Is a != b?  %d\n", a != b); // True (1)

    // `>` (Greater than)
    printf("Is a > b?   %d\n", a > b); // True (1)

    // `<` (Less than)
    printf("Is a < b?   %d\n", a < b); // False (0)

    // `>=` (Greater than or equal to)
    printf("Is a >= 10? %d\n", a >= 10); // True (1)

    // `<=` (Less than or equal to)
    printf("Is b <= 3?  %d\n", b <= 3); // True (1)
    printf("\n");

    // --- Part 3: Logical Operators ---

    /*
     * LOGICAL OPERATORS are used to combine or modify logical (true/false) expressions.
     */
    printf("--- Part 3: Logical Operators ---\n");
    int is_player_alive = 1; // 1 for true
    int has_key = 0;         // 0 for false
    printf("Player is alive: %d, Player has key: %d\n\n", is_player_alive, has_key);

    // `&&` (Logical AND) - evaluates to true ONLY if BOTH operands are true.
    printf("Can open door (is_player_alive && has_key)? %d\n", is_player_alive && has_key);

    // `||` (Logical OR) - evaluates to true if AT LEAST ONE operand is true.
    printf("Is player alive OR has key? %d\n", is_player_alive || has_key);

    // `!` (Logical NOT) - inverts the truth value of its operand.
    printf("The opposite of has_key (!has_key) is: %d\n", !has_key);
    printf("\n");

    // --- Part 4: Operator Precedence ---
    printf("--- Part 4: Operator Precedence ---\n");
    /*
     * Just like in math (PEMDAS/BODMAS), operators in C have a default order
     * of evaluation called OPERATOR PRECEDENCE. For example, `*` and `/` are
     * evaluated before `+` and `-`.
     */
    int result1 = 5 + 2 * 10;             // 2*10 is done first, then 5 is added.
    printf("5 + 2 * 10 = %d\n", result1); // Prints 25, not 70.

    /*
     * You can use parentheses `()` to force a specific order of evaluation,
     * just like in math. It's often a good idea to use parentheses to make
     * your code clearer, even when not strictly necessary.
     */
    int result2 = (5 + 2) * 10;             // (5+2) is done first.
    printf("(5 + 2) * 10 = %d\n", result2); // Prints 70.

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * In this lesson, you learned about C's fundamental operators:
 * - Arithmetic (`+`, `-`, `*`, `/`, `%`) for calculations.
 * - Relational (`==`, `!=`, `>`, `<`, `>=`, `<=`) for comparisons.
 * - Logical (`&&`, `||`, `!`) for combining true/false conditions.
 *
 * You also learned about integer division, the modulus operator, and how to
 * use parentheses `()` to control the order of operations.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 4_basic_operators 4_basic_operators.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./4_basic_operators`
 *    - On Windows (WSL): `./4_basic_operators`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 4_basic_operators 4_basic_operators.c
./4_basic_operators

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Read two integers with scanf and print their sum, difference, product, integer quotient and remainder.
  2. Print 7 / 2, 7.0 / 2 and (double)7 / 2. Explain each result.
  3. Write an expression that is 1 when an integer year is a leap year (divisible by 4, and not by 100 unless also by 400), and test it on 1900, 2000 and 2024.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/04-basic-operators/ in the repository and on this lesson’s page on the website.

Conditional Statements

What you’ll learn: making decisions with if, else and else if chains, and combining conditions with && and ||.

Before you start: Lessons 1-4, especially the operators from Lesson 4.

Our programs so far have been linear; they execute every line of code from top to bottom in the same order every time. To create powerful and intelligent programs, we need them to be able to make decisions.

CONDITIONAL STATEMENTS allow us to control the flow of our program’s execution. They use the relational and logical operators from the previous lesson to evaluate conditions. If a condition is true (evaluates to a non-zero value), one block of code is executed. If it’s false (evaluates to 0), that block is skipped, and optionally, another block is executed.

The primary tool for this is the if statement.

The if statement is the simplest form of a conditional. It executes a block of code ONLY if its condition is true.

Syntax:

if (condition)
{
    // Code to execute if 'condition' is true
}

For example:

if (score == 100)
{
    printf("Congratulations on a perfect score!\n");
}

The else statement provides an alternative block of code to execute when the if condition is false.

Syntax:

if (condition)
{
    // Code to execute if 'condition' is true
}
else
{
    // Code to execute if 'condition' is false
}

The lesson uses it to tell even numbers from odd ones (remember % from Lesson 4):

if (number_to_check % 2 == 0)
{
    printf("%d is an even number.\n", number_to_check);
}
else
{
    printf("%d is an odd number.\n", number_to_check);
}

To check for multiple, mutually exclusive conditions, you can chain else if statements. The program will check each condition in order. As soon as it finds a true condition, it runs that block and skips the rest of the entire chain. The final else is optional and acts as a “catch-all” if none of the preceding conditions were true.

if (user_grade >= 90)
{
    printf("Your letter grade is A.\n");
}
else if (user_grade >= 80)
{
    printf("Your letter grade is B.\n");
}
else if (user_grade >= 70)
{
    printf("Your letter grade is C.\n");
}
else if (user_grade >= 60)
{
    printf("Your letter grade is D.\n");
}
else
{
    printf("Your letter grade is F.\n");
}

A grade of 85 fails the first test, passes user_grade >= 80, prints “B” and skips everything after it, which is why the >= 70 test never sees it.

Combining Conditions

We can use logical operators (&&, ||) to create more complex conditions. For example, to check if a grade is a B (80-89):

if (user_grade >= 80 && user_grade < 90)
{
    printf("This is a solid B.\n");
}

Full Source

/**
 * @file 5_conditional_statements.c
 * @brief Part 1, Lesson 5: Conditional Statements
 * @author dunamismax
 * @date 06-15-2025
 *
 * This lesson introduces conditional statements, which allow a program
 * to make decisions and execute different code blocks based on specific conditions.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Our programs so far have been linear; they execute every line of code from
 * top to bottom in the same order every time. To create powerful and intelligent
 * programs, we need them to be able to make decisions.
 *
 * CONDITIONAL STATEMENTS allow us to control the flow of our program's execution.
 * They use the relational and logical operators from the previous lesson to
 * evaluate conditions. If a condition is true (evaluates to a non-zero value),
 * one block of code is executed. If it's false (evaluates to 0), that block
 * is skipped, and optionally, another block is executed.
 *
 * The primary tool for this is the `if` statement.
 */

#include <stdio.h>

int main(void)
{
    // --- Part 1: The `if` Statement ---

    /*
     * The `if` statement is the simplest form of a conditional. It executes a
     * block of code ONLY if its condition is true.
     *
     * Syntax:
     * if (condition) {
     *     // Code to execute if 'condition' is true
     * }
     */
    int score = 100;

    printf("--- Part 1: The 'if' Statement ---\n");
    printf("Initial score: %d\n", score);

    // This condition `score == 100` is true, so the printf inside the braces will run.
    if (score == 100)
    {
        printf("Congratulations on a perfect score!\n");
    }

    // This condition `score > 100` is false, so this block is skipped.
    if (score > 100)
    {
        printf("This message will not be printed.\n");
    }
    printf("\n");

    // --- Part 2: The `if-else` Statement ---

    /*
     * The `else` statement provides an alternative block of code to execute
     * when the `if` condition is false.
     *
     * Syntax:
     * if (condition) {
     *     // Code to execute if 'condition' is true
     * } else {
     *     // Code to execute if 'condition' is false
     * }
     */
    int number_to_check = 0;

    printf("--- Part 2: The 'if-else' Statement ---\n");
    printf("Enter a whole number: ");

    /*
     * Remember the input check from Lesson 3? Now you can read it fully.
     * `scanf` returns how many items it read. The condition
     * `scanf(...) != 1` is TRUE when reading failed, so the `if` block runs
     * and the program stops before it can use a number it never received.
     */
    if (scanf("%d", &number_to_check) != 1)
    {
        printf("That was not a whole number. Exiting.\n");
        return 1;
    }

    // We use the modulus operator `%` to check for an even number.
    // If a number divided by 2 has a remainder of 0, it's even.
    if (number_to_check % 2 == 0)
    {
        printf("%d is an even number.\n", number_to_check);
    }
    else
    {
        printf("%d is an odd number.\n", number_to_check);
    }
    printf("\n");

    // --- Part 3: The `if-else if-else` Chain ---

    /*
     * To check for multiple, mutually exclusive conditions, you can chain
     * `else if` statements. The program will check each condition in order.
     * As soon as it finds a true condition, it runs that block and skips the
     * rest of the entire chain. The final `else` is optional and acts as a
     * "catch-all" if none of the preceding conditions were true.
     */
    int user_grade = 0;

    printf("--- Part 3: The 'if-else if-else' Chain ---\n");
    printf("Enter your numerical grade (0-100): ");
    if (scanf("%d", &user_grade) != 1)
    {
        printf("That was not a whole number. Exiting.\n");
        return 1;
    }

    if (user_grade >= 90)
    {
        printf("Your letter grade is A.\n");
    }
    else if (user_grade >= 80)
    {
        printf("Your letter grade is B.\n");
    }
    else if (user_grade >= 70)
    {
        printf("Your letter grade is C.\n");
    }
    else if (user_grade >= 60)
    {
        printf("Your letter grade is D.\n");
    }
    else
    {
        printf("Your letter grade is F.\n");
    }

    /*
     * Note on logical combinations:
     * We can use logical operators (`&&`, `||`) to create more complex conditions.
     * For example, to check if a grade is a B (80-89):
     */
    if (user_grade >= 80 && user_grade < 90)
    {
        printf("This is a solid B.\n");
    }

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * In this lesson, you've learned how to give your program a brain.
 *
 * Key Takeaways:
 * - The `if` statement executes code only if a condition is true.
 * - The `if-else` statement provides an alternative path for when the condition is false.
 * - The `if-else if-else` chain allows you to test a series of conditions in order,
 *   executing only the first one that is true.
 * - These constructs are the fundamental building blocks for creating logic
 *   and making your programs smart and responsive.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 5_conditional_statements 5_conditional_statements.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./5_conditional_statements`
 *    - On Windows (WSL): `./5_conditional_statements`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 5_conditional_statements 5_conditional_statements.c
./5_conditional_statements

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Read a temperature in Celsius and print “freezing”, “cold”, “mild” or “hot” for ranges you choose.
  2. Reject grades outside 0-100 with an error message before the grade chain runs.
  3. Read three integers and print the largest. Make sure it works when two of them are equal.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/05-conditional-statements/ in the repository and on this lesson’s page on the website.

Loops

What you’ll learn: repeating code with for, while and do-while loops, and reading input in a loop without hanging on bad input or end of input.

Before you start: Lessons 1-5.

Imagine you needed to print “Hello!” five times. You could write:

printf("Hello!\n");
printf("Hello!\n");
printf("Hello!\n");
printf("Hello!\n");
printf("Hello!\n");

This is tedious and not scalable. What if you needed to do it 500 times? This is where LOOPS come in. A LOOP is a programming structure that repeats a sequence of instructions until a specific condition is met. Each single execution of the loop’s body is called an ITERATION.

C has three main types of loops:

  1. The for loop
  2. The while loop
  3. The do-while loop

The for loop is ideal when you know exactly how many times you want to repeat a block of code. It has a very specific structure with three parts inside its parentheses, separated by semicolons.

for (INITIALIZATION; CONDITION; POST-ITERATION)
{
    // Code to be repeated
}
  1. INITIALIZATION: A statement that runs only ONCE before the loop starts. It’s typically used to declare and initialize a counter variable.
  2. CONDITION: An expression that is checked BEFORE each iteration. If the condition is true, the loop body runs. If it’s false, the loop terminates.
  3. POST-ITERATION: A statement that runs AFTER each iteration. It’s typically used to increment or decrement the counter variable. i++ is shorthand for i = i + 1, and i-- for i = i - 1.

The lesson counts down from 5:

for (int i = 5; i > 0; i--)
{
    printf("%d...\n", i);
}

It prints 5, 4, 3, 2 and 1. When i reaches 0, the condition i > 0 is false and the loop ends.

The while loop is simpler. It repeats a block of code AS LONG AS its condition remains true. It’s useful when you don’t know the exact number of iterations beforehand.

while (condition)
{
    // Code to be repeated
}

The condition is checked BEFORE each iteration. The lesson’s menu keeps asking until the user chooses 4:

int menu_choice = 0;
while (menu_choice != 4)
{
    // print the menu and read a new menu_choice
}

CRITICAL: You must ensure that something inside the loop’s body will eventually make the condition false. Otherwise, you will create an INFINITE LOOP, and your program will never end!

The do-while loop is a variation of the while loop. The key difference is that the condition is checked AT THE END of the loop’s body.

do
{
    // Code to be repeated
} while (condition);

This means a do-while loop is GUARANTEED to execute at least once. Note the semicolon after the condition.

This makes it perfect for situations like input validation, where you need to get the input first before you can check if it’s valid.

Reading Input Inside a Loop

Loops and scanf together are a classic source of infinite loops, so this lesson handles every result scanf can return:

  • 1: the number was read. Use it.
  • EOF: the input has ended (for example, Ctrl+D), so no more input will ever arrive. Leave the loop instead of asking forever.
  • 0: the user typed something that is not a number, like abc. scanf leaves that text waiting in the INPUT BUFFER, so the next call would fail on the same text again. Throw the rest of the line away first:
int leftover = getchar();
while (leftover != '\n' && leftover != EOF)
{
    leftover = getchar();
}

getchar() reads ONE character and returns it as an int. It returns an int rather than a char so that it can also return EOF.

Full Source

/**
 * @file 6_loops.c
 * @brief Part 1, Lesson 6: Loops
 * @author dunamismax
 * @date 06-15-2025
 *
 * This lesson introduces loops, which are control structures that allow
 * a block of code to be executed repeatedly.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Imagine you needed to print "Hello!" five times. You could write:
 * printf("Hello!\n");
 * printf("Hello!\n");
 * printf("Hello!\n");
 * printf("Hello!\n");
 * printf("Hello!\n");
 *
 * This is tedious and not scalable. What if you needed to do it 500 times?
 * This is where LOOPS come in. A LOOP is a programming structure that repeats a
 * sequence of instructions until a specific condition is met. Each single
 * execution of the loop's body is called an ITERATION.
 *
 * C has three main types of loops:
 * 1. The `for` loop
 * 2. The `while` loop
 * 3. The `do-while` loop
 */

#include <stdio.h>

int main(void)
{
    // --- Part 1: The `for` Loop ---

    /*
     * The `for` loop is ideal when you know exactly how many times you want to
     * repeat a block of code. It has a very specific structure with three parts
     * inside its parentheses, separated by semicolons.
     *
     * for (INITIALIZATION; CONDITION; POST-ITERATION) {
     *     // Code to be repeated
     * }
     *
     * 1. INITIALIZATION: A statement that runs only ONCE before the loop starts.
     *    It's typically used to declare and initialize a counter variable.
     * 2. CONDITION: An expression that is checked BEFORE each iteration. If the
     *    condition is true, the loop body runs. If it's false, the loop terminates.
     * 3. POST-ITERATION: A statement that runs AFTER each iteration. It's
     *    typically used to increment or decrement the counter variable. `i++` is
     *    shorthand for `i = i + 1`.
     */
    printf("--- Part 1: The 'for' Loop (Countdown) ---\n");

    // Let's create a countdown from 5 down to 1.
    // Initialization: `int i = 5`
    // Condition: `i > 0` (loop as long as i is greater than 0)
    // Post-iteration: `i--` (decrement i by 1 after each loop; shorthand for i = i - 1)
    for (int i = 5; i > 0; i--)
    {
        printf("%d...\n", i);
    }
    printf("Blast off!\n\n");

    // --- Part 2: The `while` Loop ---

    /*
     * The `while` loop is simpler. It repeats a block of code AS LONG AS its
     * condition remains true. It's useful when you don't know the exact number
     * of iterations beforehand.
     *
     * while (condition) {
     *     // Code to be repeated
     * }
     *
     * The condition is checked BEFORE each iteration.
     *
     * CRITICAL: You must ensure that something inside the loop's body will
     * eventually make the condition false. Otherwise, you will create an
     * INFINITE LOOP, and your program will never end!
     */
    printf("--- Part 2: The 'while' Loop (Simple Menu) ---\n");

    int menu_choice = 0;

    // Loop as long as the user has not chosen option 4 to quit.
    while (menu_choice != 4)
    {
        printf("Menu:\n");
        printf("1. Start New Game\n");
        printf("2. Load Game\n");
        printf("3. Options\n");
        printf("4. Quit\n");
        printf("Enter your choice: ");

        /*
         * Reading input inside a loop needs extra care. As you saw in Lesson 3,
         * `scanf` returns how many items it read. We save that in a variable so
         * we can handle each of its three possible outcomes.
         */
        int items_read = scanf("%d", &menu_choice); // This updates the loop variable.

        if (items_read == 1)
        {
            printf("You chose: %d\n\n", menu_choice);
        }
        else if (items_read == EOF)
        {
            /*
             * The input has ended (for example, the user pressed Ctrl+D), so no
             * more choices will ever arrive. If we did nothing, `menu_choice`
             * would never become 4 and this would be an INFINITE LOOP. Setting
             * it to 4 makes the loop condition false, so the loop ends.
             */
            printf("\nNo more input. Quitting.\n");
            menu_choice = 4;
        }
        else
        {
            /*
             * The user typed something that is not a number, like `abc`.
             * `scanf` refuses to read it and leaves it waiting in the INPUT
             * BUFFER. If we just looped back, the next `scanf` would see the
             * same `abc`, fail again, and loop forever!
             *
             * To fix this, we throw away everything up to the end of the line.
             * `getchar()` reads ONE character from the input and returns it. We
             * keep reading until we reach the newline `'\n'` (the user pressed
             * Enter) or `EOF` (the input ended). `getchar` returns an `int`, not
             * a `char`, so that it can also return `EOF`.
             */
            printf("That was not a number. Please try again.\n\n");
            int leftover = getchar();
            while (leftover != '\n' && leftover != EOF)
            {
                leftover = getchar();
            }
        }
    }
    printf("Thanks for playing!\n\n");

    // --- Part 3: The `do-while` Loop ---

    /*
     * The `do-while` loop is a variation of the `while` loop. The key difference
     * is that the condition is checked AT THE END of the loop's body.
     *
     * This means a `do-while` loop is GUARANTEED to execute at least once.
     *
     * This makes it perfect for situations like input validation, where you need
     * to get the input first *before* you can check if it's valid.
     */
    printf("--- Part 3: The 'do-while' Loop (Input Validation) ---\n");
    int secret_number = 0;

    do
    {
        printf("Please enter a number between 1 and 10: ");
        int items_read = scanf("%d", &secret_number);

        if (items_read == EOF)
        {
            // No input left, so we can never get a valid number. Stop here.
            printf("\nNo more input. Exiting.\n");
            return 1;
        }
        if (items_read == 0)
        {
            // Not a number. Throw away the rest of the line, just like above,
            // and set an invalid value so the loop asks again.
            int leftover = getchar();
            while (leftover != '\n' && leftover != EOF)
            {
                leftover = getchar();
            }
            secret_number = 0;
        }

        // This check happens AFTER the user has already entered a number.
        if (secret_number < 1 || secret_number > 10)
        {
            printf("Invalid input. Please try again.\n");
        }

    } while (secret_number < 1 || secret_number > 10); // The condition is checked here.

    printf("You successfully entered the number %d.\n", secret_number);

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * In this lesson, you learned how to make your program perform repetitive tasks.
 *
 * Key Takeaways:
 * - Loops are used to execute a block of code multiple times.
 * - The `for` loop is great for when you know the number of iterations in advance.
 *   It consists of an initializer, a condition, and a post-iteration step.
 * - The `while` loop is great for when you want to loop as long as a condition is
 *   true, and the number of iterations isn't fixed.
 * - The `do-while` loop is similar to `while`, but it always executes its body at
 *   least once because the condition is checked at the end.
 * - When a loop reads input, handle every result `scanf` can return. Bad input
 *   stays in the input buffer until you discard it, and `EOF` means no more input
 *   will ever arrive. Ignoring either one is a classic cause of infinite loops.
 *
 * Mastering loops is a massive step towards writing complex and useful programs.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 6_loops 6_loops.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./6_loops`
 *    - On Windows (WSL): `./6_loops`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 6_loops 6_loops.c
./6_loops

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Print the multiplication table for a number the user enters, from 1 times to 10 times.
  2. Use a while loop to add up numbers the user types until they enter 0, then print the total.
  3. Write a number-guessing game: keep asking until the user types 7, and count the guesses. Make sure garbage input and Ctrl+D do not make it loop forever.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/06-loops/ in the repository and on this lesson’s page on the website.

Functions

What you’ll learn: writing your own functions: prototypes, definitions, parameters, arguments and return values.

Before you start: Lessons 1-6.

As programs grow larger, putting all the code inside the main function becomes messy, hard to read, and difficult to maintain. If you have a task that needs to be performed multiple times, you don’t want to copy and paste the same block of code over and over.

A FUNCTION is a named, self-contained block of code that performs a specific task. Think of printf and scanf–they are functions that someone else wrote to perform the tasks of printing and scanning. Now, you will learn to write your own.

Using functions allows us to follow the “DRY” principle: Don’t Repeat Yourself.

There are three key parts to using a function:

  1. The DECLARATION (also called the PROTOTYPE): Informs the compiler about the function’s existence, its name, what type of value it returns, and what parameters it accepts.
  2. The DEFINITION: The actual code that makes up the function’s body.
  3. The CALL: The statement that executes the function.

A FUNCTION PROTOTYPE is a declaration that tells the compiler what a function looks like before it’s actually defined. This is crucial because the compiler reads files from top to bottom. If main tries to call a function that the compiler hasn’t seen yet, it will generate an error. Prototypes solve this.

A prototype consists of:

  • The return type of the function.
  • The name of the function.
  • The data types of the parameters it accepts, in order.
  • A semicolon at the end.

The lesson’s three prototypes sit above main:

void print_welcome_message(void);
void display_character_level(int character_level);
int calculate_damage(int strength, int weapon_power);

The main function will now act as a manager, calling our other functions to perform their specific tasks:

print_welcome_message();
int player_level = 15;
display_character_level(player_level);
int total_damage = calculate_damage(20, 8);

Below main, we provide the full DEFINITIONS for our functions. A definition includes the function’s header (which looks like the prototype, but without the semicolon) and its body inside curly braces {}.

This is an example of a function that takes no arguments and returns no value. void as a return type means it doesn’t send any value back. (void) as the parameter list means it doesn’t accept any input.

void print_welcome_message(void)
{
    printf("--- Welcome to the Function Demo! ---\n\n");
}

This function accepts one piece of data: an integer. Inside this function, that integer is known by the PARAMETER name character_level. A PARAMETER is a special local variable that holds the value of the ARGUMENT passed during the call.

void display_character_level(int character_level)
{
    printf("Your character is level %d.\n\n", character_level);
}

When main calls display_character_level(player_level), the ARGUMENT is player_level (15), and inside the function the PARAMETER character_level starts out holding a copy of that value.

This function takes two integers as input and, importantly, it has a RETURN VALUE. The return keyword does two things:

  1. It immediately ends the execution of this function.
  2. It sends the value that follows it back to wherever the function was called.
int calculate_damage(int strength, int weapon_power)
{
    int calculated_value = strength + (weapon_power * 2);
    return calculated_value;
}

So calculate_damage(20, 8) returns 20 + (8 * 2), which is 36, and main stores it in total_damage.

Full Source

/**
 * @file 7_functions.c
 * @brief Part 1, Lesson 7: Functions
 * @author dunamismax
 * @date 06-15-2025
 *
 * This lesson introduces functions, which are the fundamental building blocks
 * for organizing code into reusable, modular pieces.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * As programs grow larger, putting all the code inside the `main` function
 * becomes messy, hard to read, and difficult to maintain. If you have a task
 * that needs to be performed multiple times, you don't want to copy and paste
 * the same block of code over and over.
 *
 * A FUNCTION is a named, self-contained block of code that performs a specific
 * task. Think of `printf` and `scanf`--they are functions that someone else wrote
 * to perform the tasks of printing and scanning. Now, you will learn to write
 * your own.
 *
 * Using functions allows us to follow the "DRY" principle: Don't Repeat Yourself.
 *
 * There are three key parts to using a function:
 * 1. The DECLARATION (also called the PROTOTYPE): Informs the compiler about the
 *    function's existence, its name, what type of value it returns, and what
 *    parameters it accepts.
 * 2. The DEFINITION: The actual code that makes up the function's body.
 * 3. The CALL: The statement that executes the function.
 */

#include <stdio.h>

// --- Part 1: Function Declarations (Prototypes) ---

/*
 * A FUNCTION PROTOTYPE is a declaration that tells the compiler what a function
 * looks like *before* it's actually defined. This is crucial because the compiler
 * reads files from top to bottom. If `main` tries to call a function that the
 * compiler hasn't seen yet, it will generate an error. Prototypes solve this.
 *
 * A prototype consists of:
 * - The return type of the function.
 * - The name of the function.
 * - The data types of the parameters it accepts, in order.
 * - A semicolon at the end.
 */

// Prototype for a simple function that takes nothing and returns nothing.
void print_welcome_message(void);

// Prototype for a function that takes an integer as input and returns nothing.
// The name `character_level` inside the parentheses is optional in a prototype,
// but can be good for documentation.
void display_character_level(int character_level);

// Prototype for a function that takes two integers and returns an integer.
int calculate_damage(int strength, int weapon_power);

// --- Part 2: The `main` Function (The Caller) ---

/*
 * The `main` function will now act as a manager, calling our other functions
 * to perform their specific tasks.
 */
int main(void)
{
    // FUNCTION CALL: To execute a function, you write its name followed by
    // parentheses. This is a call to `print_welcome_message`.
    print_welcome_message();

    int player_level = 15;
    // This call passes the *value* of `player_level` (which is 15) as an
    // ARGUMENT to the `display_character_level` function.
    display_character_level(player_level);

    // Here, we call `calculate_damage` and store its result.
    // The values 20 and 8 are the ARGUMENTS we pass.
    int total_damage = calculate_damage(20, 8);

    printf("With 20 strength and a weapon power of 8...\n");
    printf("Total calculated damage is: %d\n", total_damage);

    return 0; // End the main program
}

// --- Part 3: Function Definitions (The Implementation) ---

/*
 * Below `main`, we provide the full DEFINITIONS for our functions. A definition
 * includes the function's header (which looks like the prototype, but without
 * the semicolon) and its body inside curly braces `{}`.
 */

/**
 * @brief Prints a standard welcome message to the console.
 *
 * This is an example of a function that takes no arguments and returns no value.
 * `void` as a return type means it doesn't send any value back.
 * `(void)` as the parameter list means it doesn't accept any input.
 */
void print_welcome_message(void)
{
    printf("--- Welcome to the Function Demo! ---\n\n");
}

/**
 * @brief Displays a character's level.
 * @param character_level The level to be displayed.
 *
 * This function accepts one piece of data: an integer. Inside this function,
 * that integer is known by the PARAMETER name `character_level`. A PARAMETER is a
 * special local variable that holds the value of the ARGUMENT passed during the call.
 */
void display_character_level(int character_level)
{
    printf("Your character is level %d.\n\n", character_level);
}

/**
 * @brief Calculates damage based on strength and weapon power.
 * @param strength The character's strength attribute.
 * @param weapon_power The power rating of the equipped weapon.
 * @return The total calculated damage as an integer.
 *
 * This function takes two integers as input and, importantly, it has a
 * RETURN VALUE. The `return` keyword does two things:
 * 1. It immediately ends the execution of this function.
 * 2. It sends the value that follows it back to wherever the function was called.
 */
int calculate_damage(int strength, int weapon_power)
{
    int calculated_value = strength + (weapon_power * 2);
    return calculated_value; // Send this value back to the caller (`main`)
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * In this lesson, you've unlocked one of the most powerful organizational tools in C.
 *
 * Key Takeaways:
 * - Functions let you break down large problems into smaller, manageable, and
 *   reusable pieces of code.
 * - A FUNCTION PROTOTYPE (declaration) tells the compiler a function exists before it's defined.
 * - A FUNCTION DEFINITION contains the actual code that runs.
 * - A FUNCTION CALL executes the function.
 * - PARAMETERS are the variables in a function's definition that accept input.
 * - ARGUMENTS are the actual values you pass to a function when you call it.
 * - The `return` keyword sends a value back from the function to the caller.
 * - A `void` return type means the function does not return any value.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 7_functions 7_functions.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./7_functions`
 *    - On Windows (WSL): `./7_functions`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 7_functions 7_functions.c
./7_functions

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Write int square(int n) and use it to print the squares of 1 to 10.
  2. Write int max_of(int a, int b) and use it twice to find the largest of three numbers.
  3. Move a function’s definition above main and delete its prototype. Does it still compile? Now move it below main again, still without the prototype, and read the error.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/07-functions/ in the repository and on this lesson’s page on the website.

Arrays

What you’ll learn: arrays: declaring them, zero-based indexing, initializer lists, and looping over every element.

Before you start: Lessons 1-7, especially for loops from Lesson 6.

So far, we have only used variables that can hold one value at a time. For example, int score = 100;. But what if you need to store the scores for an entire class of 30 students? Declaring 30 separate variables (score1, score2, etc.) would be extremely inefficient.

An ARRAY is a data structure that can store a fixed-size, sequential collection of elements of the SAME data type. Think of it as a row of numbered boxes, where each box holds a value of the same type.

To declare an array, you specify the data type of its elements, the name of the array, and the number of elements it can hold (its size) in square brackets [].

The following line declares an array named high_scores that can hold exactly 5 integers:

int high_scores[5];

Accessing Array Elements

You access individual elements of an array using an INDEX in square brackets. C uses ZERO-BASED INDEXING. This is a critical concept. It means the first element is at index 0, the second at index 1, and so on. For an array of size 5, the valid indices are 0, 1, 2, 3, and 4.

high_scores[0] = 980; // the first element
high_scores[4] = 799; // the fifth (and last) element
printf("The highest score is: %d\n", high_scores[0]);

Accessing an index outside of this range (like high_scores[5]) leads to UNDEFINED BEHAVIOR, a common source of bugs and crashes in C programs.

Manually assigning each element is tedious. You can initialize an array when you declare it using an initializer list in curly braces {}.

If you provide an initializer list, you can let the compiler figure out the size of the array by leaving the square brackets empty:

double temperatures[] = {72.5, 75.0, 69.8, 80.1, 85.3}; // Size is 5
char grades[] = {'A', 'B', 'A', 'C', 'B', 'A'};         // Size is 6

The real power of arrays is realized when you combine them with loops. A for loop is perfect for iterating through an array, performing an action on each element. The loop counter doubles as the index:

for (int i = 0; i < 5; i++)
{
    printf("  Day %d: %.1f\n", i + 1, temperatures[i]);
}

i runs from 0 to 4, exactly the valid indices. Writing i <= 5 instead would read one element past the end.

Full Source

/**
 * @file 8_arrays.c
 * @brief Part 1, Lesson 8: Arrays
 * @author dunamismax
 * @date 06-15-2025
 *
 * This lesson introduces arrays, a fundamental data structure for storing
 * collections of elements of the same type.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * So far, we have only used variables that can hold one value at a time. For
 * example, `int score = 100;`. But what if you need to store the scores for
 * an entire class of 30 students? Declaring 30 separate variables (`score1`,
 * `score2`, etc.) would be extremely inefficient.
 *
 * An ARRAY is a data structure that can store a fixed-size, sequential
 * collection of elements of the SAME data type. Think of it as a row of
 * numbered boxes, where each box holds a value of the same type.
 */

#include <stdio.h>

int main(void)
{
    // --- Part 1: Declaring and Initializing an Array ---

    /*
     * To declare an array, you specify the data type of its elements, the name
     * of the array, and the number of elements it can hold (its size) in
     * square brackets `[]`.
     *
     * The following line declares an array named `high_scores` that can hold
     * exactly 5 integers.
     */
    int high_scores[5]; // An array of 5 integers.

    /*
     * ACCESSING ARRAY ELEMENTS:
     * You access individual elements of an array using an INDEX in square brackets.
     * C uses ZERO-BASED INDEXING. This is a critical concept. It means the
     * first element is at index 0, the second at index 1, and so on.
     * For an array of size 5, the valid indices are 0, 1, 2, 3, and 4.
     *
     * Accessing an index outside of this range (like `high_scores[5]`) leads to
     * UNDEFINED BEHAVIOR, a common source of bugs and crashes in C programs.
     */
    printf("--- Part 1: Assigning and Accessing Array Elements ---\n");
    high_scores[0] = 980; // Assign 980 to the first element
    high_scores[1] = 950; // Assign 950 to the second element
    high_scores[2] = 875;
    high_scores[3] = 820;
    high_scores[4] = 799; // The fifth (and last) element

    printf("The highest score is: %d\n", high_scores[0]);
    printf("The third highest score is: %d\n", high_scores[2]);
    printf("\n");

    // --- Part 2: Initializer Lists ---

    /*
     * Manually assigning each element is tedious. You can initialize an array
     * when you declare it using an initializer list in curly braces `{}`.
     *
     * If you provide an initializer list, you can let the compiler figure out
     * the size of the array by leaving the square brackets empty.
     */
    printf("--- Part 2: Using an Initializer List ---\n");
    double temperatures[] = {72.5, 75.0, 69.8, 80.1, 85.3}; // Size is 5
    char grades[] = {'A', 'B', 'A', 'C', 'B', 'A'};         // Size is 6

    printf("The first temperature recorded was: %.1f\n", temperatures[0]);
    printf("The fourth student's grade was: %c\n", grades[3]);
    printf("\n");

    // --- Part 3: Iterating Over an Array ---

    /*
     * The real power of arrays is realized when you combine them with loops.
     * A `for` loop is perfect for iterating through an array, performing an
     * action on each element.
     */
    printf("--- Part 3: Iterating Over an Array with a 'for' loop ---\n");
    printf("All recorded temperatures:\n");

    // We will loop from index 0 up to (but not including) 5.
    // The loop counter `i` is used as the array index.
    for (int i = 0; i < 5; i++)
    {
        printf("  Day %d: %.1f\n", i + 1, temperatures[i]);
    }
    printf("\n");

    // Let's use a loop to calculate the sum of all high scores.
    int total_score = 0;
    for (int i = 0; i < 5; i++)
    {
        total_score = total_score + high_scores[i];
    }
    printf("Sum of all high scores: %d\n", total_score);

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * In this lesson, you've learned to manage collections of data.
 *
 * Key Takeaways:
 * - An ARRAY is a fixed-size collection of elements of the same type.
 * - C uses ZERO-BASED INDEXING, where the first element is at index 0.
 * - Accessing an array element is done with `array_name[index]`.
 * - You can initialize an array with a list of values like `int arr[] = {1, 2, 3};`.
 * - Loops, especially `for` loops, are essential for processing each element in an array.
 *
 * NOTE: For now, we manually kept track of the array's size (e.g., `i < 5`). In
 * future lessons, we will learn more robust ways to handle array sizes.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 8_arrays 8_arrays.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./8_arrays`
 *    - On Windows (WSL): `./8_arrays`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 8_arrays 8_arrays.c
./8_arrays

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Find and print the largest value in high_scores.
  2. Read 5 integers from the user into an array, then print them in reverse order.
  3. Compute the average of temperatures as a double and print it with one decimal place.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/08-arrays/ in the repository and on this lesson’s page on the website.

Strings

What you’ll learn: C strings as char arrays with a null terminator, the string.h functions strlen, strcpy, strcat and strcmp, and snprintf, which builds a string without overflowing its buffer.

Before you start: Lesson 8.

Up to this point, we’ve only seen string “literals” (text in double quotes) used directly in printf. We haven’t stored or manipulated them.

THE BIG IDEA: C does not have a built-in string data type like many other languages. Instead, a C STRING is simply an ARRAY of characters (char).

But how does the computer know where the string ends in the array?

The Null Terminator

C strings follow a crucial convention: they are “null-terminated”. This means a special character, the NULL TERMINATOR \0, is placed after the last actual character in the array to mark the end of the string.

So, the string “Hello” is stored in a char array as:

'H' 'e' 'l' 'l' 'o' '\0'

It requires 6 characters of storage, not 5! This is a very important concept.

All standard C functions that work with strings rely on this \0 character.

The easiest way to declare and initialize a string is to use a string literal. The compiler automatically adds the null terminator \0 for you:

char greeting[] = "Hello, C programmer!";

You could also build a string one character at a time, but then you must add the \0 yourself:

char name[] = {'A', 'l', 'i', 'c', 'e', '\0'};

The %s format specifier in printf is used for strings. When printf receives a char array with %s, it prints characters one by one until it finds the null terminator \0.

Because strings are so common, C provides a standard library of functions to work with them. We included <string.h> at the top to get access.

strlen(): String Length

strlen(message) counts the characters before the \0 (the terminator is not counted). It returns a size_t, an unsigned type for sizes, so it is printed with %zu:

printf("The length of the message (strlen) is: %zu\n", strlen(message));

strcpy(): String Copy

You CANNOT assign one string to another using =. char another_string[20]; another_string = message; <– THIS IS WRONG!

You must copy the characters from the source to the destination. WARNING: The destination array must be large enough to hold the source string, including its null terminator!

char destination[50];
char source[] = "Some text to be copied.";
strcpy(destination, source);

strcat(): String Concatenate (Join)

This function appends one string to the end of another. WARNING: Again, the destination string must have enough space for the combined result!

char full_greeting[50] = "Welcome, ";
char user[] = "dunamismax";
strcat(full_greeting, user);

snprintf(): Build a String Safely

snprintf works like printf, but writes into a buffer, and you give it the buffer’s size. It never writes past the end: text that does not fit is cut short instead of overflowing. Its return value is how many characters the whole text needed, so you can tell when that happened. When you cannot be sure a result fits, use snprintf instead of strcpy and strcat.

char short_greeting[10];
int needed = snprintf(short_greeting, sizeof(short_greeting), "Welcome, %s", user);

strcmp(): String Compare

You CANNOT compare strings using ==. if (str1 == str2) <– THIS IS WRONG! It compares memory locations, not content.

strcmp() compares two strings lexicographically (like in a dictionary). It returns:

  • 0 if the strings are identical.
  • A negative value if the first string comes before the second.
  • A positive value if the first string comes after the second.

So the test for “the same string” is == 0:

if (strcmp(pass1, pass2) == 0)

"password123" and "Password123" are different, because case matters.

Full Source

/**
 * @file 9_strings.c
 * @brief Part 1, Lesson 9: Strings
 * @author dunamismax
 * @date 06-15-2025
 *
 * This lesson covers how to work with strings, which are one of the most
 * common types of data in programming.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Up to this point, we've only seen string "literals" (text in double quotes)
 * used directly in `printf`. We haven't stored or manipulated them.
 *
 * THE BIG IDEA: C does not have a built-in `string` data type like many other
 * languages. Instead, a C STRING is simply an ARRAY of characters (`char`).
 *
 * But how does the computer know where the string ends in the array?
 *
 * THE NULL TERMINATOR
 * C strings follow a crucial convention: they are "null-terminated". This means
 * a special character, the NULL TERMINATOR `\0`, is placed after the last
 * actual character in the array to mark the end of the string.
 *
 * So, the string "Hello" is stored in a `char` array as:
 * ['H', 'e', 'l', 'l', 'o', '\0']
 * It requires 6 characters of storage, not 5! This is a very important concept.
 *
 * All standard C functions that work with strings rely on this `\0` character.
 */

#include <stdio.h>
#include <string.h> // We must include this new header for string manipulation functions.

int main(void)
{
    // --- Part 1: Declaring and Printing Strings ---

    /*
     * The easiest way to declare and initialize a string is to use a string
     * literal. The compiler automatically adds the null terminator `\0` for you.
     */
    char greeting[] = "Hello, C programmer!";

    printf("--- Part 1: Declaring and Printing Strings ---\n");
    /*
     * The `%s` format specifier in `printf` is used for strings. When `printf`
     * receives a `char` array with `%s`, it prints characters one by one
     * until it finds the null terminator `\0`.
     */
    printf("Our greeting string: %s\n", greeting);

    // Let's prove the null terminator exists. We'll manually initialize one.
    // This is the "hard way" but illustrates the concept perfectly.
    char name[] = {'A', 'l', 'i', 'c', 'e', '\0'};
    printf("A manually created name: %s\n\n", name);

    // --- Part 2: The `<string.h>` Library ---

    /*
     * Because strings are so common, C provides a standard library of functions
     * to work with them. We included `<string.h>` at the top to get access.
     */
    printf("--- Part 2: String Functions ---\n");

    // `strlen()` - String Length
    // This function counts the number of characters in a string *before* the
    // null terminator.
    char message[] = "This is a test.";
    // The length is 15, even though the array size is 16 (to hold the `\0`).
    printf("The message is: \"%s\"\n", message);
    printf("The length of the message (strlen) is: %zu\n", strlen(message));
    // Note: strlen returns a special unsigned integer type `size_t`. We use
    // the `%zu` format specifier to print it correctly and avoid warnings.
    printf("\n");

    // --- Part 3: Copying and Concatenating Strings ---

    printf("--- Part 3: Copying and Concatenating ---\n");

    /*
     * `strcpy()` - String Copy
     * You CANNOT assign one string to another using `=`.
     * `char another_string[20]; another_string = message;` <-- THIS IS WRONG!
     *
     * You must copy the characters from the source to the destination.
     * WARNING: The destination array must be large enough to hold the source
     * string, including its null terminator!
     *
     * `strcpy` does NOT check this for you. It keeps copying until it reaches
     * the source's `\0`, even past the end of the destination. Writing past
     * the end of an array is called a BUFFER OVERFLOW. It is undefined
     * behavior and one of the most common security bugs in C programs.
     *
     * Here it is safe because we chose the sizes: `source` holds 24 characters
     * (23 of text plus the `\0`) and `destination` holds 50. When the source comes
     * from the user or a file, you cannot know its length in advance: check it
     * with `strlen()` before copying (Lesson 17 does this), or read it with a
     * function that is told the destination's size, such as `fgets` (Lesson 14).
     */
    char destination[50]; // A buffer to copy into.
    char source[] = "Some text to be copied.";

    strcpy(destination, source); // Copies `source` into `destination`.
    printf("Result of strcpy: %s\n", destination);

    /*
     * `strcat()` - String Concatenate (join)
     * This function appends one string to the end of another.
     * WARNING: Again, the destination string must have enough space for the
     * combined result! `strcat` does not check either. "Welcome, " (9 characters)
     * plus "dunamismax" (10) plus `\0` needs 20 characters, and we have 50.
     */
    char full_greeting[50] = "Welcome, "; // Initialize with enough space.
    char user[] = "dunamismax";

    strcat(full_greeting, user); // Appends `user` to `full_greeting`.
    printf("Result of strcat: %s\n", full_greeting);

    /*
     * `snprintf()` - the bounded way to build a string
     * `snprintf` works like `printf`, but it writes into a buffer instead of
     * the screen, and you tell it the buffer's size. It never writes more than
     * that, `\0` included: text that does not fit is cut short instead of
     * overflowing. When you cannot be sure a result fits, as with text a user
     * typed, use `snprintf` instead of `strcpy` and `strcat`.
     *
     * Here the buffer holds 10 characters, so only "Welcome, " (9) and the
     * `\0` fit. `snprintf` returns how many characters the WHOLE text needed;
     * if that is not less than the buffer's size, the text was cut short.
     * (`sizeof` gives a `size_t`; 10 fits in an `int`, so the cast is safe.)
     */
    char short_greeting[10];
    int needed = snprintf(short_greeting, sizeof(short_greeting), "Welcome, %s", user);
    printf("Result of snprintf: %s\n", short_greeting);
    if (needed >= (int)sizeof(short_greeting))
    {
        printf("(Cut short safely: the whole text needs %d characters.)\n", needed);
    }
    printf("\n");

    // --- Part 4: Comparing Strings ---

    printf("--- Part 4: Comparing Strings ---\n");

    /*
     * `strcmp()` - String Compare
     * You CANNOT compare strings using `==`.
     * `if (str1 == str2)` <-- THIS IS WRONG! It compares memory locations, not content.
     *
     * `strcmp()` compares two strings lexicographically (like in a dictionary).
     * It returns:
     *   - 0 if the strings are identical.
     *   - A negative value if the first string comes before the second.
     *   - A positive value if the first string comes after the second.
     */
    char pass1[] = "password123";
    char pass2[] = "Password123"; // Case matters!
    char pass3[] = "password123";

    if (strcmp(pass1, pass2) == 0)
    {
        printf("\"%s\" and \"%s\" are the same.\n", pass1, pass2);
    }
    else
    {
        printf("\"%s\" and \"%s\" are different.\n", pass1, pass2);
    }

    if (strcmp(pass1, pass3) == 0)
    {
        printf("\"%s\" and \"%s\" are the same.\n", pass1, pass3);
    }

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Congratulations on completing Part 1! Strings are a huge concept.
 *
 * Key Takeaways:
 * - A C string is a `char` array ending with a null terminator `\0`.
 * - The `%s` format specifier is used to print strings.
 * - The `<string.h>` header provides essential functions for strings.
 * - `strlen()` gets the length (not including `\0`).
 * - `strcpy()` copies one string to another.
 * - `strcat()` joins one string to the end of another.
 * - Neither `strcpy()` nor `strcat()` checks the destination's size. Make sure
 *   it is big enough, or you get a BUFFER OVERFLOW.
 * - `snprintf()` builds a string in a buffer of a size you give it and never
 *   writes past the end; use it when the text might not fit.
 * - `strcmp()` compares the content of two strings.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 9_strings 9_strings.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./9_strings`
 *    - On Windows (WSL): `./9_strings`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 9_strings 9_strings.c
./9_strings

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Write a loop that counts the characters in a string without calling strlen, by stopping at '\0'.
  2. Count how many times the letter s appears in message.
  3. Make full_greeting smaller, for example char full_greeting[12], and think about what strcat would do. Why must the destination be big enough?

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/09-strings/ in the repository and on this lesson’s page on the website.

Pointers

What you’ll learn: what a pointer is, how & and * work, and changing a variable through a pointer.

Before you start: Lessons 1-9.

Welcome to Part 2 of your C journey! You’ve mastered the fundamentals, and now we’re diving deeper. This lesson introduces POINTERS, arguably the most powerful and unique feature of the C language.

Don’t be intimidated! The concept is simple: Instead of holding a value (like 5, or ‘c’), a POINTER holds a memory ADDRESS. It’s like having a note that says “the data you want is over there” instead of holding the data itself.

Why Are Pointers Important?

Pointers allow for highly efficient code and are essential for many advanced topics, including dynamic memory allocation, building complex data structures (like the linked lists we’ll see later), and allowing functions to modify the original variables you pass to them. Mastering pointers is mastering C.

Full Source

/**
 * @file 10_pointers.c
 * @brief Part 2, Lesson 10: Pointers
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for pointers.
 * It explains the core concepts of memory addresses, pointer declaration,
 * the address-of operator, and the dereference operator through structured
 * comments and provides a runnable example of their implementation.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Welcome to Part 2 of your C journey! You've mastered the fundamentals, and now
 * we're diving deeper. This lesson introduces POINTERS, arguably the most
 * powerful and unique feature of the C language.
 *
 * Don't be intimidated! The concept is simple:
 * Instead of holding a value (like 5, or 'c'), a POINTER holds a memory ADDRESS.
 * It's like having a note that says "the data you want is over there" instead of
 * holding the data itself.
 *
 * WHY ARE POINTERS IMPORTANT?
 * Pointers allow for highly efficient code and are essential for many advanced
 * topics, including dynamic memory allocation, building complex data structures
 * (like the linked lists we'll see later), and allowing functions to modify
 * the original variables you pass to them. Mastering pointers is mastering C.
 */

#include <stdio.h> // We need this for printf and to use NULL

// --- Part 1: Variables and Their Memory Addresses ---

// Every variable you declare is stored somewhere in your computer's memory (RAM).
// Each location in memory has a unique ADDRESS, like a house number on a street.

// The ADDRESS-OF operator (`&`) gives you the memory address of a variable.

// --- Part 2: What is a Pointer? ---

// A POINTER is a special kind of variable that is designed to store a memory ADDRESS.

// DECLARING A POINTER:
// You declare a pointer by specifying the type of data it will point to,
// followed by an asterisk (*), and then the pointer's name.
//
// SYNTAX: data_type *pointer_name;
//
// Example: `int *p_number;` declares a pointer named `p_number` that is
//          intended to hold the address of an `int` variable.
//
// It's a very good practice to initialize pointers to NULL. NULL is a special
// value that means "this pointer doesn't point to anything valid." This helps
// prevent bugs from using a pointer that points to a random, garbage address.

// --- Part 3: The Dereference Operator (*) ---

// The asterisk `*` has a second job. When used with an existing pointer variable
// (not in its declaration), it acts as the DEREFERENCE operator.
//
// DEREFERENCING means "go to the address stored in this pointer and get the
// value that is located there."

int main(void)
{
    // --- DEMONSTRATION 1: Getting a Variable's Address ---

    int score = 94; // A regular integer variable. It has a value (94) and an address.

    printf("--- Part 1: Variable Addresses ---\n");
    printf("The value of the 'score' variable is: %d\n", score);

    // We use the address-of operator (&) to get its memory location.
    // The `%p` format specifier is used to print addresses in a standard hexadecimal format.
    printf("The memory address of 'score' is: %p\n\n", (void *)&score);

    // --- DEMONSTRATION 2: Declaring and Using a Pointer ---

    printf("--- Part 2 & 3: Pointers in Action ---\n");

    // Declare a pointer that can hold the address of an integer.
    // We initialize it to NULL for safety.
    int *p_score = NULL;

    printf("Initial value of p_score (a safe pointer): %p\n", (void *)p_score);

    // Now, let's make the pointer 'point to' our 'score' variable.
    // We assign the address of 'score' to the pointer 'p_score'.
    p_score = &score;

    printf("Value of p_score after assignment: %p (Notice it's score's address!)\n", (void *)p_score);
    printf("Address of the pointer itself (p_score): %p\n\n", (void *)&p_score); // Pointers have their own address too!

    // --- DEMONSTRATION 3: Dereferencing a Pointer ---

    printf("--- Part 4: Dereferencing ---\n");
    // To get the value stored at the address the pointer holds, we DEREFERENCE it with *.
    printf("Value at the address p_score points to: %d\n\n", *p_score);

    // --- DEMONSTRATION 4: Modifying a Variable via its Pointer ---
    // This is where the true power of pointers starts to show. We can change the
    // original 'score' variable's value using only the pointer.

    printf("--- Part 5: Modifying Data via Pointer ---\n");
    printf("Original score: %d\n", score);

    printf("Changing value through the pointer...\n");
    *p_score = 100; // "Go to the address stored in p_score and set the value there to 100."

    // Let's check the original 'score' variable now.
    printf("New score: %d\n", score); // It has been changed!

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  Every variable has a value AND a memory ADDRESS.
 * 2.  The ADDRESS-OF operator `&` gets the memory address of a variable.
 * 3.  A POINTER is a variable that stores a memory address.
 * 4.  The DEREFERENCE operator `*` (when used on an existing pointer) goes to the
 *     pointer's stored address and retrieves the value at that location.
 * 5.  Pointers allow you to indirectly read and modify the variables they point to.
 * 6.  Initializing pointers to `NULL` is a critical safety practice.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 10_pointers 10_pointers.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./10_pointers`
 *    - On Windows (WSL): `./10_pointers`
 *
 * If a program of your own (or a changed copy of this one) crashes or prints
 * numbers that make no sense, a bad pointer or memory access is the usual
 * cause. Build it again with the sanitizers turned on, by adding
 * `-g -fsanitize=address,undefined` to the command above. They stop the
 * program at the first bad access and print which line did it; Lesson 36
 * explains how to read their report.
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 10_pointers 10_pointers.c
./10_pointers

If a program of your own (or a changed copy of this one) crashes or prints numbers that make no sense, a bad pointer or memory access is the usual cause. Build it again with -g -fsanitize=address,undefined added to the command. These sanitizers stop the program at the first bad access and print which line did it; Lesson 36 explains how to read their report.

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Declare a double and a pointer to it, change the value through the pointer, and print both the variable and the pointer.
  2. Write void reset(int *value) that sets the pointed-to integer to 0, and call it on score.
  3. Print the address of two neighbouring local variables. How far apart are they? (The answer depends on your compiler; there is no single right one.)

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/10-pointers/ in the repository and on this lesson’s page on the website.

Pointers and Arrays

What you’ll learn: how an array name acts as a pointer to its first element, pointer arithmetic, and the two equivalent ways to reach an element.

Before you start: Lessons 8 and 10.

In the previous lesson, you learned what a POINTER is: a variable that stores a memory address. Now, we will explore one of the most important relationships in C: the connection between pointers and arrays.

The Big Reveal

The name of an array, by itself, acts as a CONSTANT POINTER to the first element of that array.

This means an array’s name IS a memory address. This is why, in Lesson 9, we could pass a char array like message straight to strlen() and strcpy() without the & operator. The array’s name already provided the address!

(One exception: sizeof still sees the whole array. With the grades array in this lesson, sizeof(grades) is the size of all 5 integers, not of one pointer.)

This relationship enables a powerful technique called POINTER ARITHMETIC, which allows us to move between elements of an array using a pointer.

Full Source

/**
 * @file 11_pointers_and_arrays.c
 * @brief Part 2, Lesson 11: Pointers and Arrays
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for the relationship
 * between pointers and arrays. It explains that an array name is a pointer
 * to the first element and introduces the concept of POINTER ARITHMETIC.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * In the previous lesson, you learned what a POINTER is: a variable that stores
 * a memory address. Now, we will explore one of the most important relationships
 * in C: the connection between pointers and arrays.
 *
 * THE BIG REVEAL:
 * The name of an array, by itself, acts as a CONSTANT POINTER to the first
 * element of that array.
 *
 * This means an array's name IS a memory address. This is why, in Lesson 9, we
 * could pass a `char` array like `message` straight to `strlen()` and `strcpy()`
 * without the `&` operator. The array's name already provided the address!
 *
 * (One exception: `sizeof` still sees the whole array. With the `grades` array
 * below, `sizeof(grades)` is the size of all 5 integers, not of one pointer.)
 *
 * This relationship enables a powerful technique called POINTER ARITHMETIC, which
 * allows us to move between elements of an array using a pointer.
 */

#include <stdio.h>

int main(void)
{
    // Let's create an array of integers.
    // In memory, these values are stored right next to each other in a
    // single, unbroken block. This is called CONTIGUOUS memory.
    int grades[] = {85, 92, 78, 99, 67};
    int count = 5; // Number of elements in the array

    // --- Part 1: The Array Name is a Pointer ---

    printf("--- Part 1: The Array Name as a Pointer ---\n");

    // Let's prove that the array name 'grades' is just an address.
    // We will print the value of 'grades' and the address of its first element.
    printf("Value of 'grades' (the array name): %p\n", (void *)grades);
    printf("Address of the first element (&grades[0]): %p\n", (void *)&grades[0]);
    printf("They are the same!\n\n");

    // --- Part 2: Pointer Arithmetic ---

    printf("--- Part 2: Pointer Arithmetic ---\n");

    // Since the array name is a pointer, we can assign it to a real pointer variable.
    int *p_grades = grades; // Note: no `&` is needed!

    // Let's access the first element using the pointer.
    printf("First element using grades[0]: %d\n", grades[0]);
    printf("First element using *p_grades: %d\n\n", *p_grades);

    // Now for the magic. What happens if we add 1 to the pointer?
    // POINTER ARITHMETIC is smart. Adding `1` to an `int` pointer doesn't just
    // add 1 to the address. It moves the address forward by the size of ONE ELEMENT.
    // In this case, it moves forward by `sizeof(int)` bytes.

    // `*(p_grades + 1)` means "go to the address of the first element, move
    // forward by the size of one integer, and then dereference that new address."
    printf("Second element using grades[1]: %d\n", grades[1]);
    printf("Second element using *(p_grades + 1): %d\n\n", *(p_grades + 1));

    printf("Third element using grades[2]: %d\n", grades[2]);
    printf("Third element using *(p_grades + 2): %d\n\n", *(p_grades + 2));

    // --- Part 3: Equivalence of p[i] and *(p + i) ---

    printf("--- Part 3: Equivalence of Subscript and Pointer Notation ---\n");

    // The C language guarantees that for any pointer or array `p` and integer `i`,
    // the expression `p[i]` is EXACTLY THE SAME as `*(p + i)`.
    // The square bracket notation `[]` is just "syntactic sugar" to make pointer
    // arithmetic look cleaner and more familiar.

    printf("Accessing the fourth element (index 3):\n");
    printf("Using array notation grades[3]: %d\n", grades[3]);
    printf("Using pointer notation *(grades + 3): %d\n\n", *(grades + 3));

    // This even works on our pointer variable `p_grades`!
    printf("Accessing the fifth element (index 4) via our pointer variable:\n");
    printf("Using pointer notation *(p_grades + 4): %d\n", *(p_grades + 4));
    printf("Using array notation p_grades[4]: %d\n\n", p_grades[4]);

    // --- Part 4: Looping Through an Array with a Pointer ---

    printf("--- Part 4: Looping Through The Array ---\n");
    printf("Grades: ");
    for (int i = 0; i < count; i++)
    {
        // We will use pointer arithmetic to access each element
        printf("%d ", *(grades + i));
    }
    printf("\n");

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  The name of an array is a constant pointer to its first element.
 * 2.  `array_name` and `&array_name[0]` evaluate to the same memory address.
 * 3.  POINTER ARITHMETIC lets you move between elements. Adding `n` to a pointer
 *     moves it forward by `n * sizeof(element_type)` bytes in memory.
 * 4.  The standard array subscript notation `array[i]` is just a more convenient
 *     way of writing the pointer arithmetic expression `*(array + i)`. They are
 *     functionally identical.
 * 5.  This deep relationship is what makes passing arrays to functions so efficient
 *     in C--you're just passing a single address, not copying the whole array.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 11_pointers_and_arrays 11_pointers_and_arrays.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./11_pointers_and_arrays`
 *    - On Windows (WSL): `./11_pointers_and_arrays`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 11_pointers_and_arrays 11_pointers_and_arrays.c
./11_pointers_and_arrays

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Loop over grades with a pointer that you move with p++ instead of an index.
  2. Write int sum(const int *values, int count) and call it with grades.
  3. Print sizeof(grades) in main and sizeof(values) inside your sum function. Why are they different?

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/11-pointers-and-arrays/ in the repository and on this lesson’s page on the website.

Structs

What you’ll learn: grouping related data in a struct, reaching members with ., and with -> through a pointer.

Before you start: Lessons 9-11.

So far, our variables have held a single piece of data (like an int or a double), and our arrays have held multiple pieces of the SAME type of data.

But what if we want to represent a more complex, real-world object? Think of a student. A student has a name (a string), an ID number (an integer), and a GPA (a double). These are all different data types, but they all logically belong together.

This is where a STRUCT (short for structure) comes in. A STRUCT is a user-defined data type that groups together related variables of potentially different types into a single unit.

Full Source

/**
 * @file 12_structs.c
 * @brief Part 2, Lesson 12: Structs
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for structs.
 * It explains how to define and use custom data types to group related
 * variables, and how to access their members using both the dot (.) and
 * arrow (->) operators.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * So far, our variables have held a single piece of data (like an `int` or a
 * `double`), and our arrays have held multiple pieces of the SAME type of data.
 *
 * But what if we want to represent a more complex, real-world object?
 * Think of a student. A student has a name (a string), an ID number (an integer),
 * and a GPA (a double). These are all different data types, but they all
 * logically belong together.
 *
 * This is where a STRUCT (short for structure) comes in. A STRUCT is a
 * user-defined data type that groups together related variables of potentially
 * different types into a single unit.
 */

#include <stdio.h>
#include <string.h> // We need this for strcpy() to handle strings

// --- Part 1: Defining a Struct ---

// We define the blueprint for our new data type using the `struct` keyword.
// This definition doesn't create any variables yet; it just tells the compiler
// what a "Student" looks like. It's like creating a blueprint for a house.
// By convention, struct names often start with a capital letter.
struct Student
{
    // These are the MEMBERS of the struct.
    char name[50];
    int student_id;
    double gpa;
};

// --- Part 2: Pointers to Structs ---

// Just like with any other data type (`int *`, `char *`), we can have pointers
// to structs. A pointer to a struct stores the memory address of a struct
// variable.
//
// When we want to access a struct's member through a pointer, we can't use the
// dot (.) operator directly. We use the ARROW OPERATOR (->).

int main(void)
{
    // --- DEMONSTRATION 1: Creating and Using a Struct Variable ---
    printf("--- Part 1: Creating and Accessing a Struct ---\n");

    // Now we can declare a variable of our new `struct Student` type.
    // This is like building an actual house from the blueprint.
    struct Student student1;

    // To access the members of a struct variable, we use the DOT OPERATOR (.).
    // Let's assign some values to student1's members.
    // For strings, we must use `strcpy` from <string.h> as we can't assign to an array directly.
    // Remember from Lesson 9 that `strcpy` never checks sizes. This copy is safe
    // because "Jane Doe" needs 9 characters (with its `\0`) and `name` holds 50.
    strcpy(student1.name, "Jane Doe");
    student1.student_id = 12345;
    student1.gpa = 3.8;

    // Now let's print the data to see our struct in action.
    printf("Student Name: %s\n", student1.name);
    printf("Student ID:   %d\n", student1.student_id);
    printf("Student GPA:  %.2f\n\n", student1.gpa); // .2f prints float/double to 2 decimal places

    // --- DEMONSTRATION 2: Using a Pointer to a Struct ---
    printf("--- Part 2: Pointers to Structs and the Arrow Operator ---\n");

    // Declare a pointer that can point to a `struct Student` variable.
    struct Student *p_student = NULL;

    // Assign the address of `student1` to our pointer.
    p_student = &student1;

    // Now we can access the members of `student1` through the pointer `p_student`.
    // We use the ARROW OPERATOR (->) for this. It's clean and intuitive.
    printf("Accessing data via pointer:\n");
    printf("Name: %s\n", p_student->name);
    printf("ID:   %d\n", p_student->student_id);
    printf("GPA:  %.2f\n\n", p_student->gpa);

    // We can also modify the original struct's data using the pointer.
    printf("Modifying GPA through the pointer...\n");
    p_student->gpa = 4.0;

    // Let's check the original student1 variable.
    printf("Original student1's new GPA: %.2f\n\n", student1.gpa); // It has been changed!

    // --- The Long Way: Dereferencing and Dot Operator ---
    // The arrow operator `->` is just "syntactic sugar" (a convenient shortcut).
    // The expression `p_student->gpa` is exactly equivalent to `(*p_student).gpa`.
    // This means "first, DEREFERENCE the pointer to get the actual struct, then
    // use the DOT OPERATOR on that struct."
    // The parentheses are required because the dot operator has higher precedence
    // than the dereference operator (*).
    printf("--- Bonus: The Long Way to Access Members via Pointer ---\n");
    printf("Accessing ID with (*p_student).student_id: %d\n", (*p_student).student_id);
    printf("See? It's the same, but `->` is much easier to read and type!\n");

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  A STRUCT lets you create your own custom data types by grouping multiple
 *     variables (called MEMBERS) into one logical unit.
 * 2.  You first define the struct's blueprint, then you can declare variables
 *     of that new type.
 * 3.  Use the DOT OPERATOR (`.`) to access members of a struct variable directly.
 *     Example: `my_struct.member`
 * 4.  Use the ARROW OPERATOR (`->`) to access members of a struct through a pointer.
 *     Example: `my_pointer_to_struct->member`
 * 5.  The arrow operator `p->m` is a convenient shortcut for `(*p).m`.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 12_structs 12_structs.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./12_structs`
 *    - On Windows (WSL): `./12_structs`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 12_structs 12_structs.c
./12_structs

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Add an int age member to struct Student, set it and print it.
  2. Make an array of three students and print them all with a loop.
  3. Write void print_student(const struct Student *s) and use it instead of the repeated printf calls.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/12-structs/ in the repository and on this lesson’s page on the website.

Dynamic Memory Allocation

What you’ll learn: asking for memory at run time with malloc, checking the result, and giving it back with free.

Before you start: Lessons 10-12.

Until now, the size of all our variables and arrays had to be known when we wrote the program (at COMPILE-TIME). For example, int numbers[10]; creates an array that can hold exactly 10 integers. It can’t hold 9, and it can’t hold 11.

But what if we don’t know how much memory we need until the program is running? What if we want to ask the user “How many students do you want to enter?” and then create an array of just the right size?

This is where DYNAMIC MEMORY ALLOCATION comes in. It’s the ability to request memory from the operating system at RUNTIME.

The Stack and the Heap

Local variables (like int x; inside main) are stored on a memory region called the STACK. The STACK is fast and memory is managed for you automatically. When a function ends, its variables on the stack are destroyed.

Dynamically allocated memory comes from a different, large pool of memory called the HEAP. The HEAP is more flexible, but there’s a catch: YOU are responsible for managing it. When you are done with memory from the HEAP, you MUST give it back to the system yourself.

Full Source

/**
 * @file 13_dynamic_memory_allocation.c
 * @brief Part 2, Lesson 13: Dynamic Memory Allocation
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for dynamic memory allocation.
 * It explains the concepts of the stack vs. the heap, and introduces the
 * functions `malloc()`, `free()`, and the `sizeof` operator.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Until now, the size of all our variables and arrays had to be known when we
 * wrote the program (at COMPILE-TIME). For example, `int numbers[10];` creates
 * an array that can hold exactly 10 integers. It can't hold 9, and it can't hold 11.
 *
 * But what if we don't know how much memory we need until the program is running?
 * What if we want to ask the user "How many students do you want to enter?" and
 * then create an array of just the right size?
 *
 * This is where DYNAMIC MEMORY ALLOCATION comes in. It's the ability to request
 * memory from the operating system at RUNTIME.
 *
 * THE STACK AND THE HEAP
 * Local variables (like `int x;` inside `main`) are stored on a memory region
 * called the STACK. The STACK is fast and memory is managed for you automatically.
 * When a function ends, its variables on the stack are destroyed.
 *
 * Dynamically allocated memory comes from a different, large pool of memory
 * called the HEAP. The HEAP is more flexible, but there's a catch:
 * YOU are responsible for managing it. When you are done with memory from the
 * HEAP, you MUST give it back to the system yourself.
 */

#include <stdio.h>
#include <stdlib.h> // `malloc` and `free` are declared in the Standard Library header

// --- Part 1: `malloc` - Memory Allocation ---
// The `malloc()` function is used to request a block of memory from the HEAP.
//
// - It takes one argument: the number of BYTES you want to allocate.
// - It returns a "void pointer" (`void*`) to the start of that memory block.
//   A `void*` is a generic pointer. In C it converts automatically to the
//   pointer type we need (e.g., `int*`, `char*`), so a CAST like `(double *)`
//   is optional. We write one below to make the type visible; many C
//   programmers leave it out.
// - If `malloc()` cannot find enough free memory, it returns `NULL`. You MUST
//   always check for this!

// --- Part 2: `sizeof` - Getting The Size of a Type ---
// How do we know how many bytes an `int` or a `struct` takes up? The size can
// be different on different computers. The `sizeof` operator solves this.
// `sizeof(int)` will give us the number of bytes for a single integer.
// This makes our code portable and readable.
//
// The common pattern for `malloc` is:
// pointer = (type *)malloc(number_of_elements * sizeof(type));
// (or, without the optional cast: pointer = malloc(number_of_elements * sizeof(type));)

// --- Part 3: `free` - Giving Memory Back ---
// When you are finished with memory you allocated with `malloc()`, you MUST
// release it using the `free()` function.
//
// If you don't, you create a MEMORY LEAK. The program holds onto memory it
// no longer needs. In a long-running program, this can eventually use up all
// available memory and crash the program or even the system.
//
// `free()` takes one argument: the pointer you got from `malloc()`.

int main(void)
{
    int num_students = 0;
    double *gpa_list = NULL; // A pointer to hold the address of our dynamic array.
                             // It's good practice to initialize it to NULL.

    printf("How many student GPAs do you want to store? ");

    // We are about to pass this number to `malloc`, so it MUST be valid.
    // First check that `scanf` actually read a number (it returns 1 on success),
    // then reject non-positive counts. The `||` operator stops at the first true
    // condition, so if reading failed we never even look at `num_students`.
    if (scanf("%d", &num_students) != 1 || num_students <= 0)
    {
        printf("Invalid number of students. Exiting.\n");
        return 1; // Exit with an error code.
    }

    // --- DEMONSTRATION: The `malloc`, use, `free` cycle ---

    // 1. ALLOCATE: Request memory from the heap.
    // We want space for `num_students` doubles.
    printf("Allocating memory for %d doubles...\n", num_students);
    // `malloc` measures sizes in `size_t`, the unsigned type `strlen`
    // returned in Lesson 9 (`sizeof` gives one too). `num_students` is an
    // `int`, so we cast it to `size_t` ourselves. That is safe only because
    // we checked above that it is positive: a negative `int` would turn into
    // a huge unsigned number.
    gpa_list = (double *)malloc((size_t)num_students * sizeof(double));

    // 2. VALIDATE: ALWAYS check if malloc succeeded.
    if (gpa_list == NULL)
    {
        printf("Error: Memory allocation failed!\n");
        printf("The operating system could not provide the requested memory.\n");
        return 1; // Exit with an error code.
    }
    printf("Memory allocated successfully at address: %p\n\n", (void *)gpa_list);

    // 3. USE: Now we can use `gpa_list` just like a regular array.
    // Let's fill it with some sample data.
    for (int i = 0; i < num_students; i++)
    {
        gpa_list[i] = 2.5 + (i * 0.2); // Just some dummy values
    }

    // And print it back out to prove it works.
    printf("The stored GPAs are:\n");
    for (int i = 0; i < num_students; i++)
    {
        printf("Student %d GPA: %.2f\n", i + 1, gpa_list[i]);
    }
    printf("\n");

    // 4. FREE: We are done with the memory. We MUST return it.
    printf("Freeing the allocated memory...\n");
    free(gpa_list);

    // IMPORTANT: After freeing, the `gpa_list` pointer is now a DANGLING POINTER.
    // It points to memory that we no longer own. Using it can cause a crash.
    // It's a critical safety practice to set the pointer to NULL immediately
    // after freeing it to prevent accidental use.
    gpa_list = NULL;

    printf("Memory has been released and pointer has been set to NULL.\n");

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  DYNAMIC MEMORY ALLOCATION allows you to request memory at RUNTIME from the HEAP.
 * 2.  The `malloc()` function allocates a block of bytes and returns a pointer to it.
 * 3.  The `sizeof` operator should always be used with `malloc` to ensure you
 *     request the correct number of bytes, making your code portable.
 * 4.  You MUST check if `malloc` returned `NULL`, which indicates allocation failure.
 * 5.  When you are done with the memory, you MUST release it with `free()`. Failure
 *     to do so results in a MEMORY LEAK.
 * 6.  After calling `free(ptr)`, set `ptr = NULL;` to prevent using a
 *     DANGLING POINTER, which is a common and dangerous bug.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 13_dynamic_memory_allocation 13_dynamic_memory_allocation.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./13_dynamic_memory_allocation`
 *    - On Windows (WSL): `./13_dynamic_memory_allocation`
 *
 * If a program of your own (or a changed copy of this one) crashes or prints
 * numbers that make no sense, a bad pointer or memory access is the usual
 * cause. Build it again with the sanitizers turned on, by adding
 * `-g -fsanitize=address,undefined` to the command above. They stop the
 * program at the first bad access and print which line did it; Lesson 36
 * explains how to read their report.
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 13_dynamic_memory_allocation 13_dynamic_memory_allocation.c
./13_dynamic_memory_allocation

If a program of your own (or a changed copy of this one) crashes or prints numbers that make no sense, a bad pointer or memory access is the usual cause. Build it again with -g -fsanitize=address,undefined added to the command. These sanitizers stop the program at the first bad access and print which line did it; Lesson 36 explains how to read their report.

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Ask the user for each GPA instead of computing dummy values, checking every scanf.
  2. Print the average of the stored GPAs before freeing the memory.
  3. Remove the free call and build with -fsanitize=address -g (Clang or GCC on Linux, Clang on macOS). Read the leak report, then put free back.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/13-dynamic-memory-allocation/ in the repository and on this lesson’s page on the website.

File I/O

What you’ll learn: writing and reading files with fopen, fprintf, fgets and fclose, and checking each step.

Before you start: Lessons 9 and 13.

All our programs so far have had a temporary existence. When the program ends, any data it was holding in variables, arrays, or structs is lost forever.

To make our programs truly useful, we need PERSISTENCE–the ability to save data to a storage device (like a hard drive) and load it back later. This is achieved through FILE I/O (Input/Output).

The Core Concepts of File I/O

  1. The FILE Pointer: When you work with a file in C, you use a special pointer type called FILE *. This is a struct defined in <stdio.h> that holds all the information C needs to manage the connection to a file (its location, your current position in it, etc.). You never need to know what’s inside the FILE struct; you just use a pointer to it.

  2. fopen() - Opening a File: This function establishes a connection, or “stream,” to a file on your disk. It takes two arguments: the filename and a “mode” string.

    • “w”: WRITE mode. Creates a new file. If the file already exists, its contents are completely ERASED and overwritten.
    • “r”: READ mode. Opens an existing file for reading. If the file doesn’t exist, fopen() will fail.
    • “a”: APPEND mode. Opens a file to add new data to the END of it. If the file doesn’t exist, it will be created. fopen() returns a FILE * on success or NULL on failure. YOU MUST ALWAYS CHECK FOR NULL!
  3. fclose() - Closing a File: This is the essential cleanup step. It finalizes any pending writes to the disk and tells the operating system you are done with the file, releasing resources. You MUST close every file you open.

  4. Writing and Reading Functions:

    • fprintf(): Works just like printf(), but its first argument is a FILE *. It writes formatted text TO a file.
    • fgets(): Reads a line of text FROM a file. It’s safer than other functions because you specify the maximum number of characters to read, preventing buffer overflows.

Full Source

/**
 * @file 14_file_io.c
 * @brief Part 2, Lesson 14: File I/O
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for File I/O (Input/Output).
 * It explains how to write data to files and read data from them, allowing
 * programs to save and load information permanently.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * All our programs so far have had a temporary existence. When the program ends,
 * any data it was holding in variables, arrays, or structs is lost forever.
 *
 * To make our programs truly useful, we need PERSISTENCE--the ability to save
 * data to a storage device (like a hard drive) and load it back later. This is
 * achieved through FILE I/O (Input/Output).
 *
 * --- The Core Concepts of File I/O ---
 *
 * 1. The `FILE` Pointer:
 *    When you work with a file in C, you use a special pointer type called `FILE *`.
 *    This is a struct defined in `<stdio.h>` that holds all the information C
 *    needs to manage the connection to a file (its location, your current
 *    position in it, etc.). You never need to know what's inside the `FILE`
 *    struct; you just use a pointer to it.
 *
 * 2. `fopen()` - Opening a File:
 *    This function establishes a connection, or "stream," to a file on your disk.
 *    It takes two arguments: the filename and a "mode" string.
 *    - "w": WRITE mode. Creates a new file. If the file already exists, its
 *           contents are completely ERASED and overwritten.
 *    - "r": READ mode. Opens an existing file for reading. If the file doesn't
 *           exist, `fopen()` will fail.
 *    - "a": APPEND mode. Opens a file to add new data to the END of it. If the
 *           file doesn't exist, it will be created.
 *    `fopen()` returns a `FILE *` on success or `NULL` on failure. YOU MUST
 *    ALWAYS CHECK FOR `NULL`!
 *
 * 3. `fclose()` - Closing a File:
 *    This is the essential cleanup step. It finalizes any pending writes to the
 *    disk and tells the operating system you are done with the file, releasing
 *    resources. You MUST close every file you open.
 *
 * 4. Writing and Reading Functions:
 *    - `fprintf()`: Works just like `printf()`, but its first argument is a
 *      `FILE *`. It writes formatted text TO a file.
 *    - `fgets()`: Reads a line of text FROM a file. It's safer than other
 *      functions because you specify the maximum number of characters to read,
 *      preventing buffer overflows.
 */

#include <stdio.h>
#include <stdlib.h> // For exit()

int main(void)
{
    // A FILE pointer, always initialize to NULL.
    FILE *file_pointer = NULL;
    char *filename = "my_first_file.txt"; // The name of the file we will work with.

    // --- DEMONSTRATION 1: Writing to a File ---
    printf("--- Part 1: Writing to a file ---\n");

    // Step 1: Open the file in WRITE ("w") mode.
    file_pointer = fopen(filename, "w");

    // Step 2: ALWAYS check if the file opened successfully.
    if (file_pointer == NULL)
    {
        // stderr is the "standard error" stream, a good place for error messages.
        fprintf(stderr, "Error: Could not open file '%s' for writing.\n", filename);
        exit(1); // exit() terminates the program immediately.
    }

    // Step 3: Write to the file using fprintf().
    printf("Writing data to %s...\n", filename);
    fprintf(file_pointer, "Hello, File!\n");
    fprintf(file_pointer, "This is the second line.\n");
    fprintf(file_pointer, "Player: %s, Score: %d\n", "Max", 100);

    // Step 4: Close the file.
    // `fprintf` collects text in a memory buffer and writes it to the disk in
    // larger pieces. `fclose` writes whatever is still in that buffer, so it is
    // where a full disk or a lost drive shows up. Like `fopen`, it reports
    // failure through its return value: 0 means success.
    if (fclose(file_pointer) != 0)
    {
        fprintf(stderr, "Error: Could not finish writing '%s'.\n", filename);
        exit(1);
    }
    file_pointer = NULL; // Good practice to nullify the pointer after closing.
    printf("Successfully wrote to and closed the file.\n\n");

    // --- DEMONSTRATION 2: Reading from a File ---
    printf("--- Part 2: Reading from a file ---\n");

    // This buffer will hold the lines we read from the file.
    char line_buffer[256];

    // Step 1: Open the same file, but now in READ ("r") mode.
    file_pointer = fopen(filename, "r");

    // Step 2: Check for errors again. The file might have been deleted, or
    // we may not have permission to read it.
    if (file_pointer == NULL)
    {
        fprintf(stderr, "Error: Could not open file '%s' for reading.\n", filename);
        exit(1);
    }

    // Step 3: Read from the file line-by-line using fgets().
    // `fgets()` reads until it hits a newline, the end of the file, or the
    // buffer size limit is reached. It returns NULL when there is nothing left to read.
    printf("Reading data from %s:\n", filename);
    while (fgets(line_buffer, sizeof(line_buffer), file_pointer) != NULL)
    {
        // Print the line we just read from the file to the console.
        printf("%s", line_buffer);
    }

    // Step 4: Close the file.
    fclose(file_pointer);
    printf("\nSuccessfully read and closed the file.\n");

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  File I/O allows your program's data to be PERSISTENT.
 * 2.  The `FILE *` is your handle to an open file.
 * 3.  The basic workflow is always: OPEN -> VALIDATE -> READ/WRITE -> CLOSE.
 * 4.  `fopen()` opens a file with a specific mode (`"w"`, `"r"`, `"a"`). You MUST
 *     check its return value for `NULL` to handle errors.
 * 5.  `fprintf()` is like `printf()` but writes to a file stream.
 * 6.  `fgets()` is a safe and reliable way to read text line-by-line from a file.
 * 7.  `fclose()` is mandatory to save all changes and release system resources.
 *     After writing, check that it returned 0, or your data may not be saved.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 14_file_io 14_file_io.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./14_file_io`
 *    - On Windows (WSL): `./14_file_io`
 *
 * After running, check the directory! You will find a new file named
 * `my_first_file.txt` containing the text from the program.
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 14_file_io 14_file_io.c
./14_file_io

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Open the file in append mode ("a") and add a line with the current score each time the program runs.
  2. Count the lines while reading the file back and print the total at the end.
  3. Change the file name to a directory that does not exist, such as "no/such/dir/file.txt", and check that the error message appears.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/14-file-io/ in the repository and on this lesson’s page on the website.

Command-Line Arguments

What you’ll learn: reading command-line arguments with argc and argv, and converting them to numbers safely with strtol.

Before you start: Lessons 9-14.

You’ve already been using command-line arguments without even realizing it! When you compile a program like this:

cc -o my_program my_program.c

The strings -o, my_program, and my_program.c are all command-line arguments passed to the cc program. They tell cc what to do.

This is an incredibly powerful way to make your programs flexible and scriptable. Instead of prompting the user for input with scanf, you can have them provide the input when they run the program.

To access these arguments, we must use a different signature for our main function.

The main Function with Arguments

int main(int argc, char *argv[])

Let’s break this down:

  1. int argc: argc stands for “argument count”. It is an integer that holds the number of command-line arguments that were passed to your program. This count ALWAYS includes the name of the program itself as the first argument. So, argc will always be at least 1.

  2. char *argv[]: argv stands for “argument vector” (a vector is just another name for an array). It is an ARRAY OF STRINGS (or more accurately, an array of character pointers). Each element in this array is one of the command-line arguments.

    • argv[0] is always the name of the program executable.
    • argv[1] is the first argument the user actually typed.
    • argv[2] is the second argument, and so on.
    • argv[argc - 1] is the last argument.

The C standard also guarantees that argv[argc] will be a NULL pointer.

Converting Arguments to Numbers

Every argument arrives as a string, so the age "30" must be converted to an int. You will often see atoi() (“ASCII to integer”) used for this, but it is RISKY: it cannot report a problem. atoi("abc") quietly returns 0, atoi("30abc") returns 30, and a number too big for an int is undefined behavior.

This lesson uses strtol() (“string to long”) instead. Its second argument is the address of a char *, which strtol sets to the first character it could not convert:

  • If that pointer still points at the start of the string, there were no digits at all.
  • If it does not point at the \0 that ends the string, there was junk after the number.

The third argument, 10, is the number base. A number too big even for a long comes back as the largest long, which the lesson’s range check (0 to 150) rejects.

Full Source

/**
 * @file 15_command_line_arguments.c
 * @brief Part 2, Lesson 15: Command-Line Arguments
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for using command-line arguments.
 * It explains the special `main` function signature that allows a program to
 * receive and process input directly from the command line when it's executed.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * You've already been using command-line arguments without even realizing it!
 * When you compile a program like this:
 * `cc -o my_program my_program.c`
 *
 * The strings `-o`, `my_program`, and `my_program.c` are all command-line
 * arguments passed to the `cc` program. They tell `cc` what to do.
 *
 * This is an incredibly powerful way to make your programs flexible and
 * scriptable. Instead of prompting the user for input with `scanf`, you can
 * have them provide the input when they run the program.
 *
 * To access these arguments, we must use a different signature for our `main` function.
 *
 * --- The `main` Function with Arguments ---
 *
 * `int main(int argc, char *argv[])`
 *
 * Let's break this down:
 *
 * 1. `int argc`:
 *    `argc` stands for "argument count". It is an integer that holds the number
 *    of command-line arguments that were passed to your program. This count
 *    ALWAYS includes the name of the program itself as the first argument. So,
 *    `argc` will always be at least 1.
 *
 * 2. `char *argv[]`:
 *    `argv` stands for "argument vector" (a vector is just another name for an array).
 *    It is an ARRAY OF STRINGS (or more accurately, an array of character pointers).
 *    Each element in this array is one of the command-line arguments.
 *
 *    - `argv[0]` is always the name of the program executable.
 *    - `argv[1]` is the first argument the user actually typed.
 *    - `argv[2]` is the second argument, and so on.
 *    - `argv[argc - 1]` is the last argument.
 *    - The C standard also guarantees that `argv[argc]` will be a `NULL` pointer.
 */

#include <stdio.h>
#include <stdlib.h> // We need this for strtol() to convert a string to a number

// Note the new main function signature!
int main(int argc, char *argv[])
{
    // --- DEMONSTRATION 1: Printing all arguments ---
    printf("--- Part 1: Inspecting argc and argv ---\n");

    // Let's first see what `argc` contains.
    printf("Argument count (argc): %d\n", argc);

    // Now, let's loop through the `argv` array and print each argument.
    printf("Arguments (argv):\n");
    for (int i = 0; i < argc; i++)
    {
        printf("  argv[%d]: \"%s\"\n", i, argv[i]);
    }
    printf("\n");

    // --- DEMONSTRATION 2: Using the arguments ---
    printf("--- Part 2: A Practical Example ---\n");

    // A common task is to check if the user provided the correct number of arguments.
    // Let's create a simple greeter program that expects a name and an age.
    // We expect 3 arguments:
    // 1. The program name (e.g., ./15_command_line_arguments)
    // 2. A name (e.g., "Alice")
    // 3. An age (e.g., "30")
    if (argc != 3)
    {
        // If the count is wrong, print a "usage" message to standard error.
        // This is a standard practice for command-line tools.
        fprintf(stderr, "Usage: %s <name> <age>\n", argv[0]);
        fprintf(stderr, "Example: %s Alice 30\n", argv[0]);
        return 1; // Return 1 to indicate an error occurred.
    }

    // If we get here, we have the correct number of arguments.
    // `argv[1]` will be the name (which is already a string).
    char *name = argv[1];

    // `argv[2]` will be the age, but it's a STRING (e.g., "30").
    // We need to convert it to an integer.

    /*
     * You will often see `atoi()` ("ASCII to integer") used for this. It is
     * short, but RISKY: it has no way to report a problem. `atoi("abc")`
     * quietly returns 0, `atoi("30abc")` returns 30, and a number too big for
     * an `int` is undefined behavior. Your program cannot tell bad input from
     * a real 0.
     *
     * `strtol()` ("string to long") does the same job and lets us check it:
     * - The first argument is the string to convert.
     * - The second is the ADDRESS of a `char *` (the `&` from Lesson 10).
     *   `strtol` sets that pointer to the first character it could NOT
     *   convert. If it still points at the start, there were no digits at
     *   all. If it does not point at the `\0` that ends the string, there was
     *   junk after the number.
     * - The third is the number BASE: 10 for ordinary decimal numbers.
     *
     * It returns a `long`, a wider integer type. A number too big even for
     * that comes back as the largest `long`, which our range check rejects.
     */
    char *end = NULL;
    long parsed_age = strtol(argv[2], &end, 10);
    if (end == argv[2] || *end != '\0' || parsed_age < 0 || parsed_age > 150)
    {
        fprintf(stderr, "Error: The age must be a whole number from 0 to 150, not \"%s\".\n", argv[2]);
        return 1;
    }
    int age = (int)parsed_age; // Safe: we checked that it is between 0 and 150.

    printf("Hello, %s!\n", name);
    printf("You are %d years old.\n", age);
    printf("In 10 years, you will be %d.\n", age + 10);

    return 0; // Success!
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  Command-line arguments make your programs powerful and scriptable.
 * 2.  Use `int main(int argc, char *argv[])` to accept arguments.
 * 3.  `argc` is the total count of arguments, including the program's own name.
 * 4.  `argv` is an array of strings containing the actual arguments.
 * 5.  `argv[0]` is always the program's name.
 * 6.  Always check `argc` to ensure the user has provided the correct number of
 *     inputs before you try to access them in `argv`.
 * 7.  Arguments are always passed as strings. Convert them to numbers with
 *     `strtol()` (for integers) or `strtod()` (for decimals), and check that the
 *     whole string was a number. Avoid `atoi()` and `atof()`: they cannot tell
 *     you when the input was bad.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 15_command_line_arguments 15_command_line_arguments.c`
 *
 * 4. Run the executable WITH DIFFERENT ARGUMENTS to see what happens:
 *
 *    Try running with no arguments (this will fail our check):
 *    - On Linux/macOS:   `./15_command_line_arguments`
 *    - On Windows (WSL): `./15_command_line_arguments`
 *
 *    Try running with the correct arguments:
 *    - On Linux/macOS:   `./15_command_line_arguments Bob 42`
 *    - On Windows (WSL): `./15_command_line_arguments Bob 42`
 *
 *    Try running with too many arguments:
 *    - On Linux/macOS:   `./15_command_line_arguments Charlie 25 Extra`
 *
 *    Try running with an age that is not a number (this will fail our strtol check):
 *    - On Linux/macOS:   `./15_command_line_arguments Dana forty`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 15_command_line_arguments 15_command_line_arguments.c
./15_command_line_arguments Bob 42

Run it with no arguments, or with too many, to see the usage message. Run it with an age that is not a number, as in ./15_command_line_arguments Dana forty, to see the strtol check reject it.

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Print every argument with its index, using a loop from 0 to argc - 1.
  2. Write a program that adds up all of its numeric arguments, rejecting any that strtol cannot fully convert.
  3. Try the lesson with 30abc, abc and 99999999999999999999 as the age, and match each message to the check that caught it.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/15-command-line-arguments/ in the repository and on this lesson’s page on the website.

Simple Calculator

What you’ll learn: building a small command-line calculator: parsing arguments with strtod, choosing an operation, and reporting errors clearly.

Before you start: Part 2, especially Lesson 15.

Welcome to Part 3! It’s time to start building bigger things. This lesson is our first real PROJECT: a simple calculator that works from the command line.

The Goal

We want to be able to run our program like this: ./16_simple_calculator 10 + 22 And have it print the result: 10.00 + 22.00 = 32.00

Skills We Will Use

  1. Command-Line Arguments (argc, argv): To get the numbers and the operator from the user when they run the program.
  2. Data Conversion: The arguments in argv are STRINGS. We need to convert the number strings (“10”, “22”) into actual numbers (double) so we can do math with them. We’ll use the strtod() function for this. It is the decimal version of the strtol() function from Lesson 15, and it tells us when an argument is not a number.
  3. Conditional Logic (if, switch): To check if the user provided the correct input and to decide which mathematical operation to perform.
  4. Error Handling: We will provide a helpful USAGE MESSAGE if the user makes a mistake and handle potential math errors like division by zero.

The switch Statement

A SWITCH compares one value with a list of fixed values. It jumps to the case that matches, or to default when none does, and break leaves the switch. Without break, the program carries on into the next case’s code (FALL-THROUGH), which is almost never what you want. A switch works with whole-number values such as char and int, not strings or doubles.

switch (operator)
{
case '+':
    result = num1 + num2;
    break;

const Parameters

parse_number takes const char *text: a pointer to characters that are CONST. The function promises not to change the string, the compiler enforces it, and a reader can see at a glance that the string is only read.

Full Source

/**
 * @file 16_simple_calculator.c
 * @brief Part 3, Lesson 16: Simple Calculator
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file is our first full PROJECT. It combines several concepts we've
 * learned--command-line arguments, data type conversion, and conditional
 * logic--to build a complete, useful command-line tool.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Welcome to Part 3! It's time to start building bigger things. This lesson is
 * our first real PROJECT: a simple calculator that works from the command line.
 *
 * THE GOAL:
 * We want to be able to run our program like this:
 * `./16_simple_calculator 10 + 22`
 * And have it print the result: `10.00 + 22.00 = 32.00`
 *
 * SKILLS WE WILL USE:
 * 1. Command-Line Arguments (`argc`, `argv`): To get the numbers and the
 *    operator from the user when they run the program.
 * 2. Data Conversion: The arguments in `argv` are STRINGS. We need to convert
 *    the number strings ("10", "22") into actual numbers (`double`) so we can
 *    do math with them. We'll use the `strtod()` function for this. It is the
 *    decimal version of the `strtol()` function from Lesson 15, and it tells
 *    us when an argument is not a number.
 * 3. Conditional Logic (`if`, `switch`): To check if the user provided the
 *    correct input and to decide which mathematical operation to perform.
 * 4. Error Handling: We will provide a helpful USAGE MESSAGE if the user makes a
 *    mistake and handle potential math errors like division by zero.
 */

#include <stdio.h>
#include <stdlib.h> // Required for strtod() and exit()
#include <string.h> // Required for strcmp()

// --- Function Prototypes (Lesson 7) ---
// Declaring the function up front gives a summary of the file. Its
// definition, with the explanation, follows below.
int parse_number(const char *text, double *result);

/**
 * @brief Converts a string such as "10.5" to a double.
 * @param text The string to convert.
 * @param result Where to store the number. We pass a pointer so the function
 *               can fill in the caller's variable.
 * @return 1 if the WHOLE string was a number, 0 otherwise.
 *
 * `const char *text` reads as "a pointer to characters that are CONST":
 * the function promises not to change the string it is given. The compiler
 * holds it to that promise (`text[0] = 'x';` would not compile), and a reader
 * knows at a glance that the string is only read.
 *
 * `strtod` ("string to double") works like `strtol` from Lesson 15: it sets
 * `end` to the first character it could not convert. If nothing was
 * converted, or anything is left over (as in "ten" or "5x"), it is not a
 * number. You may also see `atof()` ("ASCII to float") used for this, but
 * `atof("ten")` quietly returns 0.0, so a typo would turn into a wrong answer.
 */
int parse_number(const char *text, double *result)
{
    char *end = NULL;
    *result = strtod(text, &end);
    return end != text && *end == '\0';
}

// We need argc and argv to get input from the command line.
int main(int argc, char *argv[])
{
    double num1, num2, result;
    char operator;

    // --- Step 1: Validate the Input ---
    // We need exactly four arguments:
    // argv[0]: program name
    // argv[1]: first number
    // argv[2]: operator
    // argv[3]: second number
    if (argc != 4)
    {
        // If the count is wrong, print a helpful usage message to standard error.
        fprintf(stderr, "Usage: %s <number1> <operator> <number2>\n", argv[0]);
        fprintf(stderr, "Example: %s 10.5 / 2\n", argv[0]);
        exit(1); // Exit with an error code.
    }

    // --- Step 2: Convert and Store Arguments ---

    // `parse_number` (defined above) converts each number string to a double
    // and tells us whether it really was a number.
    if (!parse_number(argv[1], &num1) || !parse_number(argv[3], &num2))
    {
        fprintf(stderr, "Error: '%s' and '%s' must both be numbers.\n", argv[1], argv[3]);
        exit(1);
    }

    // The operator is a string like "+". We only need the first character.
    // We check if the string is longer than one character, which would be invalid.
    if (strlen(argv[2]) != 1)
    {
        fprintf(stderr, "Error: Invalid operator '%s'. Operator must be a single character.\n", argv[2]);
        exit(1);
    }
    operator = argv[2][0];

    // --- Step 3: Perform the Calculation ---
    // A SWITCH statement compares one value with a list of fixed values.
    // `switch (operator)` jumps to the `case` whose value matches `operator`,
    // or to `default` when none does. `break` then leaves the switch. Without
    // it, the program would carry on into the next case's code (FALL-THROUGH),
    // which is almost never what you want. A switch works with whole-number
    // values such as `char` and `int`, not strings or doubles; for those, use
    // `if` and `else if` (Lesson 5).
    switch (operator)
    {
    case '+':
        result = num1 + num2;
        break; // `break` exits the switch statement.

    case '-':
        result = num1 - num2;
        break;

    case '*':
        // Some shells interpret * as a wildcard. Users may need to type '*'
        // to pass it correctly.
        result = num1 * num2;
        break;

    case '/':
        // This is an important EDGE CASE. We cannot divide by zero.
        if (num2 == 0)
        {
            fprintf(stderr, "Error: Division by zero is not allowed.\n");
            exit(1);
        }
        result = num1 / num2;
        break;

    default:
        // If the operator is not one of the above, it's invalid.
        fprintf(stderr, "Error: Unknown operator '%c'.\n", operator);
        fprintf(stderr, "Supported operators are: + - * /\n");
        exit(1);
    }

    // --- Step 4: Display the Result ---
    // If we get here, the calculation was successful.
    // We use %.2f to format the numbers to two decimal places for clean output.
    printf("%.2f %c %.2f = %.2f\n", num1, operator, num2, result);

    return 0; // Success!
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Congratulations! You've just built your first complete, functional command-line
 * tool. You've seen how to take user input, validate it, process it, and
 * produce a result, all while handling potential errors gracefully.
 *
 * Key Achievements in this Project:
 * - Combined multiple C features into a working application.
 * - Used `argc` and `argv` for real-world program input.
 * - Converted string data to numeric data for calculations (`strtod`), and
 *   rejected arguments that were not numbers.
 * - Implemented robust error checking for both user input and math rules.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 16_simple_calculator 16_simple_calculator.c`
 *
 * 4. Run the executable with different arguments:
 *
 *    Addition:
 *    ./16_simple_calculator 5 + 3
 *
 *    Subtraction with decimals:
 *    ./16_simple_calculator 100.5 - 50.2
 *
 *    Multiplication (you might need quotes around '*' in some terminals like bash):
 *    ./16_simple_calculator 7 '*' 6
 *
 *    Division:
 *    ./16_simple_calculator 20 / 4
 *
 *    Division by zero (this will trigger our error message):
 *    ./16_simple_calculator 10 / 0
 *
 *    Not a number (this will trigger our number check):
 *    ./16_simple_calculator ten + 5
 *
 *    Not a single-character operator (this will trigger our operator check):
 *    ./16_simple_calculator 10 plus 5
 *
 *    Too few arguments (this will trigger our usage message):
 *    ./16_simple_calculator 10 +
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 16_simple_calculator 16_simple_calculator.c
./16_simple_calculator 5 + 3

To multiply, quote the operator, as in ./16_simple_calculator 7 '*' 6. Unquoted, the shell expands * into the names of the files in the current directory.

Try the error checks too: ./16_simple_calculator ten + 5 is not a number, ./16_simple_calculator 10 plus 5 is not a single-character operator, ./16_simple_calculator 10 / 0 divides by zero, and ./16_simple_calculator 10 + prints the usage message.

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Add a ^ operator that raises the first number to a whole-number power with a loop.
  2. Add a % operator for two whole numbers, and reject it when either one is not a whole number.
  3. Run the calculator with * unquoted, as in ./16_simple_calculator 7 * 6. What does your shell do to the *, and why does the lesson quote it as '*'?

Student Record System

What you’ll learn: putting functions, structs, file I/O and input checking together in a menu-driven program that saves its records.

Before you start: Lessons 12-15.

This project is where everything comes together. We will build a complete application that can:

  1. Add new student records.
  2. Display all existing records.
  3. Save the records to a file so the data isn’t lost when the program closes.
  4. Load the records from the file when the program starts.

This is a foundational pattern for almost any data-management application.

Key Architecture Concepts

  • MODULARITY: We will break the program into small, single-purpose functions (e.g., add_student, save_to_file). This makes the code much easier to read, debug, and maintain. The main function will act as a control center.
  • DATA PERSISTENCE: By using File I/O, our application’s data will persist between runs.
  • USER INTERFACE: We’ll create a simple text-based menu to interact with the user.
  • ERROR HANDLING: The program will gracefully handle file errors and invalid user input.

Functions that change how many records there are, such as add_student, take a pointer to the count (int *count), so they can modify the original student_count in main. Functions that only read the records, such as print_all_records, take them as const: a promise that the function will not change the data.

Naming a Type with typedef

typedef (TYPE DEFINITION) gives a type a new name. The lesson defines its struct and names it Student in one go, so it can write Student s; instead of struct Student s; as in Lesson 12:

typedef struct
{
    int id;
    char name[MAX_NAME_LEN];
    double gpa;
} Student;

Checking a GPA

strtod turns text into a double, and it also accepts inf and nan (NOT A NUMBER). Every comparison with a NaN is false, so a range check written as “below or above” lets it through. The lesson asks “is it inside the range?” and negates the answer instead:

!(new_student.gpa >= 0.0 && new_student.gpa <= 4.0)

Reading the last line of a file

fgets keeps the '\n' at the end of each line it reads. A line without one either did not fit in the buffer or is the last line of a file that does not end with a newline. feof tells the two apart: it is true once a read has reached the end of the file, and then the line is complete.

Full Source

/**
 * @file 17_student_record_system.c
 * @brief Part 3, Project 17: Student Record System
 * @author dunamismax
 * @date 06-15-2025
 *
 * This project builds a menu-driven database application to manage student
 * records. It demonstrates the power of combining structs, arrays, functions,
 * and file I/O to create a persistent data management tool.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * This project is where everything comes together. We will build a complete
 * application that can:
 * 1. Add new student records.
 * 2. Display all existing records.
 * 3. Save the records to a file so the data isn't lost when the program closes.
 * 4. Load the records from the file when the program starts.
 *
 * This is a foundational pattern for almost any data-management application.
 *
 * KEY ARCHITECTURE CONCEPTS:
 * - MODULARITY: We will break the program into small, single-purpose functions
 *   (e.g., `add_student`, `save_to_file`). This makes the code much easier to
 *   read, debug, and maintain. The `main` function will act as a control center.
 * - DATA PERSISTENCE: By using File I/O, our application's data will persist
 *   between runs.
 * - USER INTERFACE: We'll create a simple text-based menu to interact with the user.
 * - ERROR HANDLING: The program will gracefully handle file errors and invalid
 *   user input.
 */

#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// --- Global Constants and Type Definitions ---
#define MAX_STUDENTS 100
#define MAX_NAME_LEN 50
#define INPUT_BUFFER_SIZE 128
#define FILENAME "students.db"

// Our main data structure for a single student.
//
// `typedef` (TYPE DEFINITION) gives a type a new name. Here it defines a
// struct and names it `Student` in one go, so we can write `Student s;`
// instead of `struct Student s;` as in Lesson 12. The struct itself has no
// tag after `struct`: we only ever use the new name.
typedef struct
{
    int id;
    char name[MAX_NAME_LEN];
    double gpa;
} Student;

// --- Function Prototypes ---
// Declaring all our functions here provides a nice overview of the program's
// capabilities and allows us to call them from `main` before they are defined.
void display_menu(void);
void add_student(Student students[], int *count);
void print_all_records(const Student students[], int count);
void save_to_file(const Student students[], int count);
void load_from_file(Student students[], int *count);
void clear_stream_remainder(FILE *stream);
int read_line_from_stream(FILE *stream, char *buffer, size_t size);
int read_line(char *buffer, size_t size);
int parse_int_value(const char *text, int *value);
int parse_double_value(const char *text, double *value);
int is_blank_string(const char *text);
int parse_student_record(char *line, Student *student);

// --- Main Function: The Program's Control Center ---
int main(void)
{
    Student all_students[MAX_STUDENTS];
    int student_count = 0;
    int choice = 0;
    char input[INPUT_BUFFER_SIZE];

    // Start by loading any existing records from our database file.
    load_from_file(all_students, &student_count);

    // This is the main application loop. It continues until the user chooses to exit.
    while (1)
    {
        display_menu();
        if (read_line(input, sizeof(input)) == 0)
        {
            printf("\nEnd of input detected. Exiting program.\n");
            break;
        }

        if (!parse_int_value(input, &choice))
        {
            printf("Invalid input. Please enter a number.\n");
            continue; // Skip the rest of the loop and start over.
        }

        switch (choice)
        {
        case 1:
            add_student(all_students, &student_count);
            break;
        case 2:
            print_all_records(all_students, student_count);
            break;
        case 3:
            save_to_file(all_students, student_count);
            break;
        case 4:
            printf("Exiting program. Goodbye!\n");
            exit(0); // exit(0) terminates the program successfully.
        default:
            printf("Invalid choice. Please try again.\n");
        }
        printf("\n"); // Add a space for readability before the next menu.
    }

    return 0;
}

// --- Function Implementations ---

/**
 * @brief Displays the main menu options to the user.
 */
void display_menu(void)
{
    printf("--- Student Record System ---\n");
    printf("1. Add Student\n");
    printf("2. Display All Records\n");
    printf("3. Save Records to File\n");
    printf("4. Exit\n");
    printf("Enter your choice: ");
}

/**
 * @brief Consumes characters until the end of the current line.
 */
void clear_stream_remainder(FILE *stream)
{
    int c;
    while ((c = fgetc(stream)) != '\n' && c != EOF)
    {
        // Consume characters until newline or end-of-file.
    }
}

/**
 * @brief Reads a full line from the provided stream into a buffer.
 * @return 1 on success, 0 on EOF/error, and -1 if the line was too long.
 */
int read_line_from_stream(FILE *stream, char *buffer, size_t size)
{
    char *newline;

    // `feof` and `ferror` answer questions about the reads so far:
    // `feof(stream)` is true once a read has reached the end of the stream,
    // `ferror(stream)` once a read has failed. Either way there is nothing
    // more to read. (A file whose last line has no '\n' reaches its end
    // while that line is read; see below.)
    if (feof(stream) || ferror(stream))
    {
        return 0;
    }

    // `fgets` takes its size as an `int`, while sizes are `size_t`. Our
    // buffers hold at most 256 bytes, so the cast cannot lose anything.
    if (fgets(buffer, (int)size, stream) == NULL)
    {
        return 0;
    }

    // `strchr` finds the '\n' that `fgets` keeps at the end of a whole line.
    newline = strchr(buffer, '\n');
    if (newline != NULL)
    {
        *newline = '\0';
        return 1;
    }

    // No '\n': either the line did not fit, or it is the last line of a
    // file that does not end with a newline. `feof` tells the two apart: it
    // is true once `fgets` has hit the end of the file, and then this line
    // is complete.
    if (!feof(stream))
    {
        clear_stream_remainder(stream);
        buffer[0] = '\0';
        return -1;
    }

    return 1;
}

int read_line(char *buffer, size_t size)
{
    return read_line_from_stream(stdin, buffer, size);
}

/**
 * @brief Parses a whole-number input and rejects trailing junk.
 */
int parse_int_value(const char *text, int *value)
{
    char *endptr;
    long parsed;

    while (isspace((unsigned char)*text))
    {
        text++;
    }

    if (*text == '\0')
    {
        return 0;
    }

    errno = 0;
    parsed = strtol(text, &endptr, 10);
    if (errno != 0 || endptr == text || parsed < INT_MIN || parsed > INT_MAX)
    {
        return 0;
    }

    while (isspace((unsigned char)*endptr))
    {
        endptr++;
    }

    if (*endptr != '\0')
    {
        return 0;
    }

    *value = (int)parsed;
    return 1;
}

/**
 * @brief Parses a floating-point value and rejects trailing junk.
 */
int parse_double_value(const char *text, double *value)
{
    char *endptr;
    double parsed;

    while (isspace((unsigned char)*text))
    {
        text++;
    }

    if (*text == '\0')
    {
        return 0;
    }

    errno = 0;
    parsed = strtod(text, &endptr);
    if (errno != 0 || endptr == text)
    {
        return 0;
    }

    while (isspace((unsigned char)*endptr))
    {
        endptr++;
    }

    if (*endptr != '\0')
    {
        return 0;
    }

    *value = parsed;
    return 1;
}

int is_blank_string(const char *text)
{
    while (*text)
    {
        if (!isspace((unsigned char)*text))
        {
            return 0;
        }
        text++;
    }

    return 1;
}

/**
 * @brief Parses one database record from the on-disk format.
 */
int parse_student_record(char *line, Student *student)
{
    char *first_comma = strchr(line, ',');
    char *second_comma;

    if (!first_comma)
    {
        return 0;
    }

    second_comma = strchr(first_comma + 1, ',');
    if (!second_comma || strchr(second_comma + 1, ',') != NULL)
    {
        return 0;
    }

    *first_comma = '\0';
    *second_comma = '\0';

    if (!parse_int_value(line, &student->id) || student->id <= 0)
    {
        return 0;
    }

    if (strlen(first_comma + 1) >= MAX_NAME_LEN ||
        is_blank_string(first_comma + 1))
    {
        return 0;
    }
    // `strcpy` does not check sizes, but this copy is safe: the check above
    // rejected any name of MAX_NAME_LEN characters or more, so the name and
    // its `\0` always fit in `student->name`.
    strcpy(student->name, first_comma + 1);

    // Written as "not in range" rather than "below or above it" because of
    // NaN, see add_student.
    if (!parse_double_value(second_comma + 1, &student->gpa) ||
        !(student->gpa >= 0.0 && student->gpa <= 4.0))
    {
        return 0;
    }

    return 1;
}

/**
 * @brief Adds a new student record to the array.
 * @param students The array of student records.
 * @param count A pointer to the current number of students. We use a pointer
 *              so we can modify the original `student_count` in `main`.
 */
void add_student(Student students[], int *count)
{
    Student new_student;
    char input[INPUT_BUFFER_SIZE];

    if (*count >= MAX_STUDENTS)
    {
        printf("Database is full. Cannot add more students.\n");
        return;
    }

    printf("Enter Student ID: ");
    if (read_line(input, sizeof(input)) != 1 ||
        !parse_int_value(input, &new_student.id) ||
        new_student.id <= 0)
    {
        printf("Invalid student ID. Record was not added.\n");
        return;
    }

    printf("Enter Student Name (commas are not allowed): ");
    if (read_line(new_student.name, sizeof(new_student.name)) != 1)
    {
        printf("Name was too long or could not be read. Record was not added.\n");
        return;
    }

    if (strchr(new_student.name, ',') != NULL)
    {
        printf("Names cannot contain commas because the save file uses commas as separators.\n");
        return;
    }

    if (is_blank_string(new_student.name))
    {
        printf("Student name cannot be empty. Record was not added.\n");
        return;
    }

    // `strtod` also accepts "inf" and "nan" (NOT A NUMBER). Every comparison
    // with a NaN is false, so `gpa < 0.0 || gpa > 4.0` would let a NaN
    // through. Asking "is it inside the range?" and negating the answer
    // rejects it: `gpa >= 0.0 && gpa <= 4.0` is false for a NaN.
    printf("Enter Student GPA: ");
    if (read_line(input, sizeof(input)) != 1 ||
        !parse_double_value(input, &new_student.gpa) ||
        !(new_student.gpa >= 0.0 && new_student.gpa <= 4.0))
    {
        printf("Invalid GPA. Enter a value between 0.0 and 4.0. Record was not added.\n");
        return;
    }

    students[*count] = new_student;
    printf("Student added successfully.\n");
    (*count)++; // Increment the total number of students.
}

/**
 * @brief Prints all student records to the console in a formatted table.
 * @param students The array of student records.
 * @param count The current number of students.
 *              `const` is used to signal that this function will not change the data.
 */
void print_all_records(const Student students[], int count)
{
    if (count == 0)
    {
        printf("No records to display.\n");
        return;
    }

    printf("\n--- All Student Records ---\n");
    printf("ID   | Name                                               | GPA\n");
    printf("-----|----------------------------------------------------|------\n");
    for (int i = 0; i < count; i++)
    {
        // %-4d: left-align integer in 4 spaces
        // %-50s: left-align string in 50 spaces
        // %5.2f: right-align double in 5 spaces, with 2 decimal places
        printf("%-4d | %-50s | %5.2f\n", students[i].id, students[i].name, students[i].gpa);
    }
    printf("------------------------------------------------------------------\n");
}

/**
 * @brief Saves the entire array of student records to a file.
 */
void save_to_file(const Student students[], int count)
{
    FILE *file = fopen(FILENAME, "w"); // "w" for write, will overwrite existing file.
    if (file == NULL)
    {
        fprintf(stderr, "Error: Could not open file '%s' for writing.\n", FILENAME);
        return;
    }

    for (int i = 0; i < count; i++)
    {
        // We save in a simple comma-separated format, so names must not contain commas.
        fprintf(file, "%d,%s,%.2f\n", students[i].id, students[i].name, students[i].gpa);
    }

    // Writes are buffered, so a full disk may only show up when `fclose` writes
    // the last of them. `ferror` reports whether any earlier write failed.
    // Only claim success when every write and the close worked.
    int write_failed = ferror(file);
    if (fclose(file) != 0 || write_failed)
    {
        fprintf(stderr, "Error: Could not finish writing '%s'. Records may not be saved.\n", FILENAME);
        return;
    }
    printf("Successfully saved %d record(s) to %s.\n", count, FILENAME);
}

/**
 * @brief Loads student records from a file into the array.
 */
void load_from_file(Student students[], int *count)
{
    FILE *file = fopen(FILENAME, "r"); // "r" for read.
    char line[INPUT_BUFFER_SIZE * 2];
    int loaded = 0;
    int skipped = 0;
    int line_status;

    if (file == NULL)
    {
        // This is not an error if it's the first time running the program.
        printf("No existing database file found. Starting fresh.\n");
        return;
    }

    while ((line_status = read_line_from_stream(file, line, sizeof(line))) != 0)
    {
        if (line_status < 0)
        {
            skipped++;
            continue;
        }

        if (line[0] == '\0')
        {
            continue;
        }

        if (*count >= MAX_STUDENTS)
        {
            skipped++;
            continue;
        }

        if (parse_student_record(line, &students[*count]))
        {
            (*count)++;
            loaded++;
        }
        else
        {
            skipped++;
        }
    }

    fclose(file);
    printf("Successfully loaded %d record(s) from %s.\n", loaded, FILENAME);
    if (skipped > 0)
    {
        printf("Skipped %d invalid record(s) while loading.\n", skipped);
    }
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Congratulations! You've built a complete database application. This project is a
 * major milestone and demonstrates a solid understanding of C's most important
 * features for building practical software.
 *
 * Key Project Achievements:
 * - A modular design using functions for each major feature.
 * - Persistent data storage using a simple comma-separated file format.
 * - A clean, interactive user menu for program control.
 * - Robust handling of user input and file system operations.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 17_student_record_system 17_student_record_system.c`
 *
 * 4. Run the executable:
 *    - On Linux/macOS:   `./17_student_record_system`
 *    - On Windows (WSL): `./17_student_record_system`
 *
 * Try adding a few students, saving, exiting the program, and running it again.
 * You'll see your records are loaded back in automatically!
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 17_student_record_system 17_student_record_system.c
./17_student_record_system

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Add a menu option that finds a student by ID and prints their record.
  2. Add a menu option that prints the average GPA of all students.
  3. Open the saved file in a text editor, make one line malformed, and see how loading handles it.

Function Pointers

What you’ll learn: storing a function’s address in a function pointer, calling through it, and passing functions as callbacks.

Before you start: Lessons 7 and 10.

You have mastered pointers to DATA (like int* or struct Student*), which store the memory address of a variable.

C takes this concept one step further: you can also have pointers to CODE. A FUNCTION POINTER is a variable that stores the memory address of a function.

This might sound strange, but it’s an incredibly powerful feature. It allows you to treat functions like any other variable:

  • You can pass a function as an argument to another function.
  • You can store functions in an array.
  • You can change which function gets called at runtime.

The most common use case is creating CALLBACKS, where you provide a generic function with a specific “helper” function for it to call back to complete its task.

Full Source

/**
 * @file 18_function_pointers.c
 * @brief Part 3, Lesson 18: Function Pointers
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for function pointers.
 * It explains how to declare, assign, and use pointers to functions,
 * enabling powerful techniques like callbacks and dynamic function calls.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * You have mastered pointers to DATA (like `int*` or `struct Student*`), which
 * store the memory address of a variable.
 *
 * C takes this concept one step further: you can also have pointers to CODE.
 * A FUNCTION POINTER is a variable that stores the memory address of a function.
 *
 * This might sound strange, but it's an incredibly powerful feature. It allows
 * you to treat functions like any other variable:
 * - You can pass a function as an argument to another function.
 * - You can store functions in an array.
 * - You can change which function gets called at runtime.
 *
 * The most common use case is creating CALLBACKS, where you provide a generic
 * function with a specific "helper" function for it to call back to complete its task.
 */

#include <stdio.h>
#include <stdlib.h>

// --- Function Prototypes (Lesson 7) ---
// Declaring the functions up front gives a summary of the file. Their
// definitions, with the explanations, follow below.
// The third parameter of `perform_calculation` is a function pointer; Part 2
// explains how to read it.
int add(int a, int b);
int subtract(int a, int b);
void perform_calculation(int x, int y, int (*operation_func)(int, int));

// --- Part 1: The Functions We'll Point To ---
// Let's define two simple functions. It's crucial that they have the
// exact same SIGNATURE (return type and parameter types).

int add(int a, int b)
{
    return a + b;
}

int subtract(int a, int b)
{
    return a - b;
}

// --- Part 2: The Callback Function ---
// Here is a generic function that takes two numbers and a function pointer
// as arguments. It will use the provided function to perform a calculation.
//
// The third parameter `int (*operation_func)(int, int)` is the function pointer.
// It says: "I expect the address of a function that takes two ints and returns an int."
void perform_calculation(int x, int y, int (*operation_func)(int, int))
{
    // First, check if the pointer is valid (not NULL)
    if (operation_func == NULL)
    {
        printf("Error: No operation function provided.\n");
        return;
    }
    int result = operation_func(x, y); // Call the function through the pointer
    printf("Performing calculation... Result is: %d\n", result);
}

int main(void)
{
    // --- DEMONSTRATION 1: Declaring and Using a Function Pointer ---
    printf("--- Part 1: Basic Function Pointer Usage ---\n");

    // This is the syntax for declaring a function pointer.
    // It must match the signature of the functions it will point to.
    // return_type (*pointer_name)(parameter_types);
    int (*p_calculate)(int, int) = NULL;

    // The parentheses around `*p_calculate` are ESSENTIAL.
    // Without them, `int *p_calculate(int, int);` would declare a
    // function named `p_calculate` that returns an `int*`.

    // ASSIGNMENT: Assign the address of the `add` function to the pointer.
    // The name of a function, like an array name, decays into a pointer.
    p_calculate = add; // You can also use `&add`, but it's not necessary.

    // CALLING: Call the function through the pointer.
    int sum = p_calculate(10, 5);
    printf("Calling via pointer (add): %d\n", sum);

    // Now, point the SAME pointer to a DIFFERENT function.
    p_calculate = subtract;

    // And call it again. The pointer now invokes different code.
    int difference = p_calculate(10, 5);
    printf("Calling via pointer (subtract): %d\n\n", difference);

    // --- DEMONSTRATION 2: Using Function Pointers as Callbacks ---
    printf("--- Part 2: Callbacks in Action ---\n");

    int a = 20;
    int b = 12;

    // Here, we call `perform_calculation` and pass the `add` function
    // as the callback. `perform_calculation` will "call back" to `add`.
    printf("Passing 'add' function as a callback:\n");
    perform_calculation(a, b, add);

    // Now we call the exact same generic function, but we give it a
    // different tool to work with.
    printf("Passing 'subtract' function as a callback:\n");
    perform_calculation(a, b, subtract);

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  A FUNCTION POINTER stores the memory address of a function.
 * 2.  The declaration syntax is critical: `return_type (*pointer_name)(params);`.
 *     The parentheses around the pointer name are mandatory.
 * 3.  You can assign the name of a compatible function directly to the pointer.
 * 4.  This allows for incredibly flexible code, primarily by enabling CALLBACKS.
 * 5.  A callback is when you pass a function (A) as an argument to another
 *     function (B), and B then calls A to perform a specific part of its task.
 *     This allows you to customize the behavior of generic functions.
 *
 * This is an advanced topic, but mastering it opens the door to designing
 * highly modular and reusable C programs.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 18_function_pointers 18_function_pointers.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./18_function_pointers`
 *    - On Windows (WSL): `./18_function_pointers`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 18_function_pointers 18_function_pointers.c
./18_function_pointers

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Write multiply and divide functions and pass each one to perform_calculation. Make divide handle a divisor of 0.
  2. Make an array of function pointers holding add and subtract, and call each one in a loop.
  3. Use the standard library’s qsort with a comparison function to sort an array of integers.

Recursion

What you’ll learn: recursion: functions that call themselves, base cases, recursive steps, and the danger of stack overflow.

Before you start: Lessons 7 and 8.

So far, when you’ve needed to repeat a task, you’ve used a loop (for or while). Today, we’re going to learn a powerful and elegant alternative: RECURSION.

What Is Recursion?

RECURSION is the process of a function calling itself.

Think of it like a set of Russian nesting dolls. You open a doll to find a slightly smaller doll inside. You open that one to find an even smaller one, and so on, until you reach the smallest, solid doll that can’t be opened.

In programming, a recursive function works the same way. It has two essential parts:

  1. THE BASE CASE: This is the condition that STOPS the recursion. It’s the “smallest doll” that doesn’t call itself again. Without a base case, a recursive function would call itself forever, leading to a crash. This is the MOST IMPORTANT part of any recursive function.

  2. THE RECURSIVE STEP: This is where the function calls itself, but with a modified argument that brings it one step closer to the base case. It’s the act of “opening the doll to find the next smaller one.”

The Danger: Infinite Recursion and Stack Overflow

What happens if you forget the base case? The function will call itself endlessly. Each time a function is called, a small amount of memory is used on the “call stack”. If the recursion never stops, it will eventually use up all the available stack memory, and the program will crash with an error called a STACK OVERFLOW.

The lesson keeps this example commented out:

// DO NOT UNCOMMENT AND RUN THIS FUNCTION.
// It is an example of what NOT to do.
void infinite_recursion(void)
{
    printf("This will run forever... and then crash!\n");
    infinite_recursion(); // No base case, no modification. Uh oh.
}

Full Source

/**
 * @file 19_recursion.c
 * @brief Part 3, Lesson 19: Recursion
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for recursion. It explains
 * the concept of a function calling itself, the importance of a base case,
 * and how recursion can be an elegant alternative to loops for some problems.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * So far, when you've needed to repeat a task, you've used a loop (`for` or `while`).
 * Today, we're going to learn a powerful and elegant alternative: RECURSION.
 *
 * WHAT IS RECURSION?
 * RECURSION is the process of a function calling itself.
 *
 * Think of it like a set of Russian nesting dolls. You open a doll to find a
 * slightly smaller doll inside. You open that one to find an even smaller one,
 * and so on, until you reach the smallest, solid doll that can't be opened.
 *
 * In programming, a recursive function works the same way. It has two essential parts:
 *
 * 1. THE BASE CASE: This is the condition that STOPS the recursion. It's the
 *    "smallest doll" that doesn't call itself again. Without a base case, a
 *    recursive function would call itself forever, leading to a crash. This is
 *    the MOST IMPORTANT part of any recursive function.
 *
 * 2. THE RECURSIVE STEP: This is where the function calls itself, but with a
 *    modified argument that brings it one step closer to the base case. It's
 *    the act of "opening the doll to find the next smaller one."
 */

#include <stdio.h>

// --- Function Prototypes (Lesson 7) ---
// Declaring the functions up front gives a summary of the file. Their
// definitions, with the explanations, follow below.
void countdown(int n);
long long factorial(int n);

// --- Part 1: A Simple Recursive Countdown ---
// This function will count down from a number `n` to 1, then print "Blastoff!".
// It's a simple way to see the base case and recursive step in action.
void countdown(int n)
{
    // BASE CASE: If n is 0 or less, we stop the recursion.
    if (n <= 0)
    {
        printf("Blastoff!\n");
        return; // Stop.
    }

    // RECURSIVE STEP:
    printf("%d...\n", n);
    countdown(n - 1); // The function calls itself with a smaller number.
}

// --- Part 2: A Classic Example - Factorial ---
// The factorial of a non-negative integer `n`, denoted by `n!`, is the
// product of all positive integers less than or equal to `n`.
// Example: 5! = 5 * 4 * 3 * 2 * 1 = 120
//
// This problem has a natural recursive definition:
// - The factorial of 0 is 1. (Base Case)
// - The factorial of any other number `n` is `n` times the factorial of `n-1`. (Recursive Step)
//
// We use `long long` for the return type because factorials grow very quickly!
long long factorial(int n)
{
    // BASE CASE: The factorial of 0 (or 1) is 1.
    if (n <= 1)
    {
        return 1;
    }

    // RECURSIVE STEP: n multiplied by the factorial of the number below it.
    return n * factorial(n - 1);
}

// --- Part 3: The Danger - Infinite Recursion and Stack Overflow ---
// What happens if you forget the base case? The function will call itself
// endlessly. Each time a function is called, a small amount of memory is used
// on the "call stack". If the recursion never stops, it will eventually use up
// all the available stack memory, and the program will crash with an error
// called a STACK OVERFLOW.

/*
// DO NOT UNCOMMENT AND RUN THIS FUNCTION.
// It is an example of what NOT to do.
void infinite_recursion(void)
{
    printf("This will run forever... and then crash!\n");
    infinite_recursion(); // No base case, no modification. Uh oh.
}
*/

int main(void)
{
    printf("--- DEMONSTRATION 1: Countdown from 5 ---\n");
    countdown(5);

    printf("\n--- DEMONSTRATION 2: Calculating Factorial of 10 ---\n");
    int number = 10;
    long long fact_result = factorial(number);
    printf("The factorial of %d is %lld.\n", number, fact_result);

    // Let's try another one.
    number = 15;
    fact_result = factorial(number);
    printf("The factorial of %d is %lld.\n", number, fact_result);

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  Recursion is a problem-solving technique where a function calls itself.
 * 2.  It's a powerful alternative to loops for problems that can be broken down
 *     into smaller, self-similar sub-problems.
 * 3.  Every recursive function MUST have a BASE CASE to prevent infinite recursion.
 * 4.  Every recursive function MUST have a RECURSIVE STEP that moves it closer
 *     to the base case.
 * 5.  Forgetting or having an incorrect base case leads to a STACK OVERFLOW crash.
 *
 * While loops are often more efficient in C, recursion can provide incredibly
 * elegant and readable solutions for certain types of problems, especially when
 * dealing with tree-like data structures we'll see later.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 19_recursion 19_recursion.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./19_recursion`
 *    - On Windows (WSL): `./19_recursion`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 19_recursion 19_recursion.c
./19_recursion

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Write a recursive int sum_to(int n) that returns 1 + 2 + … + n.
  2. Write a recursive function that prints a string backwards, one character per call.
  3. Write a recursive long long fibonacci(int n) (with fibonacci(0) = 0 and fibonacci(1) = 1) and a loop version, and time both for n = 40. Which is faster, and why?

Linked Lists

What you’ll learn: building a singly linked list with malloc: nodes, the head pointer, inserting, printing and freeing.

Before you start: Lessons 12 and 13.

So far, our primary way of storing a collection of items has been the ARRAY. Arrays are great, but they have one major limitation: they have a fixed size. If you declare int my_array[100];, you can’t store 101 items without creating a new, larger array and copying everything over.

Welcome to the LINKED LIST, a data structure that solves this problem.

What Is a Linked List?

A LINKED LIST is a sequence of data elements, which are connected together via links. Each element, called a NODE, contains two things:

  1. The DATA itself (e.g., a number, a struct, etc.).
  2. A POINTER to the next node in the sequence.

Think of it like a train. Each Node is a train car. It holds some cargo (the data) and has a coupling that connects it to the next car (the next pointer). All we need to know to find the entire train is where the first car is. This first-car pointer is called the HEAD.

To add a node at the front, insert_at_beginning takes a pointer to the head pointer (Node **), so it can modify the head pointer in main.

Full Source

/**
 * @file 20_linked_lists.c
 * @brief Part 3, Lesson 20: Linked Lists
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for a singly linked list.
 * It shows how to build one of the most fundamental dynamic data structures
 * from scratch using structs, pointers, and dynamic memory allocation.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * So far, our primary way of storing a collection of items has been the ARRAY.
 * Arrays are great, but they have one major limitation: they have a fixed size.
 * If you declare `int my_array[100];`, you can't store 101 items without
 * creating a new, larger array and copying everything over.
 *
 * Welcome to the LINKED LIST, a data structure that solves this problem.
 *
 * WHAT IS A LINKED LIST?
 * A LINKED LIST is a sequence of data elements, which are connected together via
 * links. Each element, called a NODE, contains two things:
 * 1. The DATA itself (e.g., a number, a struct, etc.).
 * 2. A POINTER to the next node in the sequence.
 *
 * Think of it like a train. Each `Node` is a train car. It holds some cargo (the
 * data) and has a coupling that connects it to the next car (the `next` pointer).
 * All we need to know to find the entire train is where the first car is. This
 * first-car pointer is called the HEAD.
 */

#include <stdio.h>
#include <stdlib.h> // For malloc() and free()

// --- Part 1: The Building Block - The Node ---

// This is the blueprint for a single "car" in our train.
// It's a SELF-REFERENTIAL struct because it contains a pointer to another
// struct of its own type (`struct Node`).
typedef struct Node
{
    int data;          // The data this node holds
    struct Node *next; // A pointer to the next node in the list
} Node;

// --- Function Prototypes (Lesson 7) ---
// Declaring the functions up front gives a summary of the file. Their
// definitions, with the explanations, follow below.
Node *create_node(int data);
void insert_at_beginning(Node **head_ref, int data);
void print_list(Node *head);
void free_list(Node **head_ref);

// --- Part 2: Core List Operations ---
// We will write functions to handle the list's main operations.

/**
 * @brief Creates a new node, allocates memory for it, and initializes its fields.
 * @param data The integer data to store in the new node.
 * @return A pointer to the newly created node.
 */
Node *create_node(int data)
{
    // Allocate memory for one Node on the HEAP.
    Node *new_node = (Node *)malloc(sizeof(Node));
    if (new_node == NULL)
    {
        fprintf(stderr, "Error: Memory allocation failed!\n");
        exit(1);
    }
    new_node->data = data; // Set the data.
    new_node->next = NULL; // The new node doesn't point to anything yet.
    return new_node;
}

/**
 * @brief Inserts a new node at the beginning of the list.
 * @param head_ref A pointer to the head pointer. We need this double pointer
 *                 so we can modify the `head` pointer in the main function.
 * @param data The data for the new node.
 */
void insert_at_beginning(Node **head_ref, int data)
{
    // 1. Create the new node.
    Node *new_node = create_node(data);

    // 2. Point the new node's `next` to what `head` is currently pointing to.
    new_node->next = *head_ref;

    // 3. Update `head` to point to our new node, making it the new first node.
    *head_ref = new_node;
}

/**
 * @brief Prints all the elements of the list from beginning to end.
 * @param head A pointer to the first node of the list.
 */
void print_list(Node *head)
{
    Node *current = head; // Start at the beginning.

    while (current != NULL)
    {
        printf("%d -> ", current->data);
        current = current->next; // Move to the next node.
    }
    printf("NULL\n"); // The end of the list points to nothing.
}

/**
 * @brief Frees all memory allocated for the list to prevent memory leaks.
 * @param head_ref A pointer to the head pointer.
 */
void free_list(Node **head_ref)
{
    Node *current = *head_ref;
    Node *temp;

    while (current != NULL)
    {
        temp = current;          // Save the current node.
        current = current->next; // Move to the next one.
        free(temp);              // Free the saved node.
    }

    // Finally, set the original head pointer in main() to NULL.
    *head_ref = NULL;
}

int main(void)
{
    // The HEAD pointer. This is our only entry point into the list.
    // An empty list is represented by a NULL head pointer.
    Node *head = NULL;

    printf("Building the linked list by inserting at the beginning...\n");

    // Insert elements. Since we insert at the beginning, the last one
    // we insert will be the first one in the list.
    insert_at_beginning(&head, 30);
    insert_at_beginning(&head, 20);
    insert_at_beginning(&head, 10);

    printf("The current list is:\n");
    print_list(head);
    printf("\n");

    printf("Adding another element, 5...\n");
    insert_at_beginning(&head, 5);

    printf("The final list is:\n");
    print_list(head);
    printf("\n");

    // CRITICAL STEP: Always clean up memory when you're done.
    printf("Freeing all nodes in the list...\n");
    free_list(&head);

    printf("List after freeing:\n");
    print_list(head); // Should print "NULL"

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  A LINKED LIST is a dynamic data structure made of NODES linked by pointers.
 * 2.  A NODE contains DATA and a POINTER to the next node.
 * 3.  The HEAD pointer is the entry point to the entire list. If `head` is `NULL`,
 *     the list is empty.
 * 4.  Nodes are created on the HEAP using `malloc()`, which gives us the flexibility
 *     to grow or shrink the list at runtime.
 * 5.  Because we use `malloc()`, we are responsible for using `free()` on every
 *     single node to prevent memory leaks.
 * 6.  To modify the head pointer from within a function, we must pass its
 *     address (a pointer to a pointer, or `Node **`).
 *
 * You have just built one of the most fundamental data structures in all of
 * computer science. Understanding linked lists is key to tackling more complex
 * structures like trees, graphs, and hash tables.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 20_linked_lists 20_linked_lists.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./20_linked_lists`
 *    - On Windows (WSL): `./20_linked_lists`
 *
 * If a program of your own (or a changed copy of this one) crashes or prints
 * numbers that make no sense, a bad pointer or memory access is the usual
 * cause. Build it again with the sanitizers turned on, by adding
 * `-g -fsanitize=address,undefined` to the command above. They stop the
 * program at the first bad access and print which line did it; Lesson 36
 * explains how to read their report.
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 20_linked_lists 20_linked_lists.c
./20_linked_lists

If a program of your own (or a changed copy of this one) crashes or prints numbers that make no sense, a bad pointer or memory access is the usual cause. Build it again with -g -fsanitize=address,undefined added to the command. These sanitizers stop the program at the first bad access and print which line did it; Lesson 36 explains how to read their report.

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Write int list_length(const Node *head).
  2. Write void insert_at_end(Node **head, int data).
  3. Write a function that deletes the first node holding a given value, and free it.

Bit Manipulation

What you’ll learn: working with individual bits: the bitwise operators, masks, shifts and integer promotion.

Before you start: Lessons 2 and 4.

C is a language that operates very close to the hardware. All data in your computer–integers, characters, etc.–is ultimately stored as a sequence of BITS (binary digits), which are either 0 or 1.

C provides a special set of BITWISE OPERATORS that allow you to manipulate these individual bits directly. This is a low-level feature that is incredibly powerful for tasks like:

  • Controlling hardware devices where each bit in a register has a meaning.
  • Writing highly efficient code for specific algorithms.
  • Storing multiple boolean (true/false) flags in a single byte.

The Bitwise Operators

  • & (bitwise AND): sets a bit to 1 if BOTH corresponding bits are 1.
  • | (bitwise OR): sets a bit to 1 if EITHER corresponding bit is 1.
  • ^ (bitwise XOR): sets a bit to 1 if the corresponding bits are DIFFERENT.
  • ~ (bitwise NOT): inverts all the bits (0s become 1s and 1s become 0s).
  • << (left shift): shifts all bits to the left by a specified number of places.
  • >> (right shift): shifts all bits to the right by a specified number of places.

Integer Promotion

C does arithmetic and bitwise operations on values at least as wide as int. A small type like uint8_t is widened (PROMOTED) to int first, so ~a flips every bit of an int, not just the 8 bits of a. For a = 5 the result is -6 as an int, which does not fit back into a uint8_t.

The lesson casts such results back to the small type:

uint8_t result_not_a = (uint8_t)~a; // keeps the low 8 bits: 250
uint8_t left_shifted = (uint8_t)(c << 2);

The cast keeps the low 8 bits, which are the ones we wanted, and it tells the reader (and the compiler’s -Wconversion warning) that dropping the rest is intended.

Full Source

/**
 * @file 21_bit_manipulation.c
 * @brief Part 3, Lesson 21: Bit Manipulation
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for bit manipulation. It
 * introduces the bitwise operators and shows how to directly manipulate the
 * individual bits of data, a powerful technique for optimization and control.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * C is a language that operates very close to the hardware. All data in your
 * computer--integers, characters, etc.--is ultimately stored as a sequence of
 * BITS (binary digits), which are either 0 or 1.
 *
 * C provides a special set of BITWISE OPERATORS that allow you to manipulate
 * these individual bits directly. This is a low-level feature that is incredibly
 * powerful for tasks like:
 * - Controlling hardware devices where each bit in a register has a meaning.
 * - Writing highly efficient code for specific algorithms.
 * - Storing multiple boolean (true/false) flags in a single byte.
 *
 * --- The Bitwise Operators ---
 *
 * &  (Bitwise AND):     Sets a bit to 1 if BOTH corresponding bits are 1.
 * |  (Bitwise OR):      Sets a bit to 1 if EITHER corresponding bit is 1.
 * ^  (Bitwise XOR):     Sets a bit to 1 if the corresponding bits are DIFFERENT.
 * ~  (Bitwise NOT):     Inverts all the bits (0s become 1s and 1s become 0s).
 * << (Left Shift):      Shifts all bits to the left by a specified number of places.
 * >> (Right Shift):     Shifts all bits to the right by a specified number of places.
 */

#include <stdio.h>
#include <stdint.h> // For uint8_t, an unsigned 8-bit integer type.

// --- Function Prototypes (Lesson 7) ---
void print_binary(uint8_t byte);

// --- A Helper Function to Visualize Bits ---
// To understand bit manipulation, you need to SEE the bits. This function
// will print the binary representation of a byte (an 8-bit number).
// We use `uint8_t` for a clear, 8-bit unsigned integer.
void print_binary(uint8_t byte)
{
    printf("0b"); // "0b" prefix indicates a binary number
    // We loop from the most significant bit (7) down to the least (0).
    for (int i = 7; i >= 0; i--)
    {
        // `(byte >> i)` shifts the bit we're interested in to the 0th position.
        // `& 1` then isolates that bit. If it's 1, the result is 1; otherwise, 0.
        printf("%d", (byte >> i) & 1);
    }
}

int main(void)
{
    // Let's use two small numbers for our demonstration.
    uint8_t a = 5; // Binary: 00000101
    uint8_t b = 9; // Binary: 00001001

    printf("--- Part 1: Basic Bitwise Operations ---\n");
    printf("a = %2d = ", a);
    print_binary(a);
    printf("\n");
    printf("b = %2d = ", b);
    print_binary(b);
    printf("\n\n");

    // Bitwise AND
    uint8_t result_and = a & b; // 00000101 & 00001001 = 00000001 (1)
    printf("a & b = %2d = ", result_and);
    print_binary(result_and);
    printf("\n");

    // Bitwise OR
    uint8_t result_or = a | b; // 00000101 | 00001001 = 00001101 (13)
    printf("a | b = %2d = ", result_or);
    print_binary(result_or);
    printf("\n");

    // Bitwise XOR
    uint8_t result_xor = a ^ b; // 00000101 ^ 00001001 = 00001100 (12)
    printf("a ^ b = %2d = ", result_xor);
    print_binary(result_xor);
    printf("\n");

    // Bitwise NOT
    // INTEGER PROMOTION: C does arithmetic and bitwise operations on values
    // at least as wide as `int`, so `a` is widened to an `int` before `~`
    // flips its bits. That flips every bit of the `int` (32 on most systems),
    // not just 8, and the result (-6 as an `int`) does not fit in a `uint8_t`.
    // The cast keeps the low 8 bits, which are exactly the 8 bits we wanted.
    // Writing the cast also tells the compiler (and the reader) that dropping
    // the rest is intended; `-Wconversion` warns when it is left out.
    uint8_t result_not_a = (uint8_t)~a; // ~00000101 = 11111010 (250)
    printf("  ~a  = %3d = ", result_not_a);
    print_binary(result_not_a);
    printf("\n\n");

    // --- Part 2: Shift Operations ---
    printf("--- Part 2: Shift Operations ---\n");
    uint8_t c = 12; // Binary: 00001100

    printf("c = %2d = ", c);
    print_binary(c);
    printf("\n");

    // Left Shift (equivalent to multiplying by 2^n)
    // `c` is promoted to `int` here too, so bits shifted past bit 7 are not
    // lost until the cast back to `uint8_t` drops them.
    uint8_t left_shifted = (uint8_t)(c << 2); // 12 * 2^2 = 12 * 4 = 48 (00110000)
    printf("c << 2 = %2d = ", left_shifted);
    print_binary(left_shifted);
    printf("\n");

    // Right Shift (equivalent to integer division by 2^n)
    uint8_t right_shifted = c >> 1; // 12 / 2^1 = 12 / 2 = 6 (00000110)
    printf("c >> 1 = %2d = ", right_shifted);
    print_binary(right_shifted);
    printf("\n\n");

    // --- Part 3: Practical Use - BITMASKS for Flags ---
    // A very common use case is to store multiple on/off states in a single byte.
    // Each bit position represents a different flag.

    printf("--- Part 3: Practical Bitmasking ---\n");
    const uint8_t FLAG_READ_ACCESS = 1 << 0;    // 00000001 (1)
    const uint8_t FLAG_WRITE_ACCESS = 1 << 1;   // 00000010 (2)
    const uint8_t FLAG_EXECUTE_ACCESS = 1 << 2; // 00000100 (4)
    const uint8_t FLAG_IS_ADMIN = 1 << 7;       // 10000000 (128)

    uint8_t user_permissions = 0; // Start with no permissions.
    printf("Initial permissions: ");
    print_binary(user_permissions);
    printf("\n");

    // 1. SETTING a bit (giving permission) using OR
    user_permissions = user_permissions | FLAG_READ_ACCESS;
    user_permissions = user_permissions | FLAG_WRITE_ACCESS;
    printf("After giving R/W:    ");
    print_binary(user_permissions);
    printf("\n");

    // 2. CHECKING a bit (do they have permission?) using AND
    if (user_permissions & FLAG_WRITE_ACCESS)
    {
        printf("User has WRITE access.\n");
    }
    if (!(user_permissions & FLAG_EXECUTE_ACCESS))
    {
        printf("User does NOT have EXECUTE access.\n");
    }
    if (!(user_permissions & FLAG_IS_ADMIN))
    {
        printf("User is NOT an administrator.\n");
    }

    // 3. CLEARING a bit (revoking permission) using AND with NOT
    user_permissions = user_permissions & ~FLAG_WRITE_ACCESS;
    printf("After revoking W:    ");
    print_binary(user_permissions);
    printf("\n");

    // 4. TOGGLING a bit (flipping its state) using XOR
    user_permissions = user_permissions ^ FLAG_READ_ACCESS; // Turn it off
    user_permissions = user_permissions ^ FLAG_READ_ACCESS; // Turn it back on
    printf("After toggling R twice:");
    print_binary(user_permissions);
    printf("\n");

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  Bitwise operators (`&`, `|`, `^`, `~`, `<<`, `>>`) allow you to directly
 *     manipulate the 0s and 1s that make up numeric data types.
 * 2.  A BITMASK is a value (often a constant) used to target specific bits in another
 *     variable for setting, clearing, or checking.
 * 3.  The common patterns for bitmasking are:
 *     - Set bit:      `flags = flags | MASK;`
 *     - Clear bit:    `flags = flags & ~MASK;`
 *     - Check bit:    `if (flags & MASK) { ... }`
 *     - Toggle bit:   `flags = flags ^ MASK;`
 * 4.  Shift operators provide a very fast way to perform multiplication and
 *     division by powers of two.
 * 5.  Small types like `uint8_t` are promoted to `int` before any operator
 *     works on them. Cast the result back (`(uint8_t)~a`) when you store it in
 *     the small type again.
 *
 * This is a low-level but essential skill for any serious C programmer.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 21_bit_manipulation 21_bit_manipulation.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./21_bit_manipulation`
 *    - On Windows (WSL): `./21_bit_manipulation`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 21_bit_manipulation 21_bit_manipulation.c
./21_bit_manipulation

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Write int count_set_bits(unsigned int value) using & and >>.
  2. Use FLAG_READ_ACCESS and FLAG_EXECUTE_ACCESS to give a user both permissions, then remove execute, printing the flags with print_binary after each step.
  3. Write uint8_t reverse_bits(uint8_t value) that reverses the order of the 8 bits, and check it with print_binary.

Preprocessor Directives

What you’ll learn: what the preprocessor does: #include, #define macros, the parentheses rule, and conditional compilation.

Before you start: Part 1 and Lesson 7.

Before your C code is ever seen by the actual compiler, it goes through a first pass by a program called the C PREPROCESSOR. The preprocessor’s job is simple: it’s a text-replacement tool that scans your code for lines starting with a hash symbol (#) and acts on them. These are called PREPROCESSOR DIRECTIVES.

You’ve been using these since day one without necessarily knowing the details. Let’s explore the most important ones.

Full Source

/**
 * @file 22_preprocessor_directives.c
 * @brief Part 3, Lesson 22: Preprocessor Directives
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for the C preprocessor.
 * It explains key directives like #include, #define, and conditional
 * compilation, which are essential for managing larger codebases.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Before your C code is ever seen by the actual compiler, it goes through a
 * first pass by a program called the C PREPROCESSOR. The preprocessor's job is
 * simple: it's a text-replacement tool that scans your code for lines starting
 * with a hash symbol (`#`) and acts on them. These are called PREPROCESSOR DIRECTIVES.
 *
 * You've been using these since day one without necessarily knowing the details.
 * Let's explore the most important ones.
 */

// --- Part 1: `#include` Revisited ---
// You know that `#include` pastes the contents of another file into this one.
// But there's a subtle difference between the two forms:

#include <stdio.h> // `<...>` : Use for standard system libraries. The preprocessor
                   //           searches for these in a list of standard system directories.

// #include "my_header.h" // `"..."` : Use for your own header files. The preprocessor
//           searches first in the directory that holds the file doing the
//           #include, and then in the standard system directories.
// This is crucial for multi-file projects.

// --- Part 2: `#define` for Constants and Macros ---
// `#define` is used to create MACROS. A macro is a fragment of code that has
// been given a name. Whenever the name is used, it is replaced by the contents
// of the macro. This is direct text substitution.

// 1. Object-like Macros (Constants)
// This tells the preprocessor: "anywhere you see PI, replace it with 3.14159".
// By convention, macro constants are in ALL_CAPS.
#define PI 3.14159
#define GREETING "Hello, World!"

// 2. Function-like Macros
// These macros can take arguments.
// THE PARENTHESES RULE: When creating function-like macros, ALWAYS surround
// each argument and the ENTIRE expression with parentheses. This prevents
// operator precedence bugs after the text substitution happens.

// BAD EXAMPLE:
#define BAD_SQUARE(x) x *x
// If you call `BAD_SQUARE(2 + 3)`, it expands to `2 + 3 * 2 + 3`, which is `2 + 6 + 3 = 11`. WRONG!

// GOOD EXAMPLE (Follow this rule!):
#define SQUARE(x) ((x) * (x))
// Now, `SQUARE(2 + 3)` expands to `((2 + 3) * (2 + 3))`, which is `5 * 5 = 25`. CORRECT!

// --- Part 3: Conditional Compilation ---
// These directives allow you to include or exclude parts of your code from
// compilation based on certain conditions. This is extremely useful.

// A common use is for debugging messages. We can define a `DEBUG` macro.
#define DEBUG

int main(void)
{
    printf("--- Part 1 & 2: Using #define Macros ---\n");
    double radius = 5.0;
    double area = PI * SQUARE(radius); // Preprocessor expands this before compilation

    printf("%s\n", GREETING);
    printf("The area of a circle with radius %.2f is %.2f\n", radius, area);

    int val = 2 + 3;
    printf("The square of (2 + 3) is %d\n\n", SQUARE(val));

    printf("--- Part 3: Conditional Compilation in Action ---\n");

// This block of code will only be included if the DEBUG macro is defined.
#ifdef DEBUG
    printf("DEBUG: This is a debug message.\n");
    printf("DEBUG: The value of 'area' is %f.\n", area);
#endif

// You can also use #ifndef (if not defined).
#ifndef RELEASE_MODE
    printf("This is not a release build.\n");
#endif

// You can also check values with #if
#if (10 > 5)
    printf("#if (10 > 5) is true, so this line is compiled.\n");
#endif

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  The PREPROCESSOR runs before the compiler, performing text-based operations
 *     on your code based on directives starting with `#`.
 * 2.  `#include <...>` is for system libraries; `#include "..."` is for your own files.
 * 3.  `#define` creates macros for constants or simple functions. ALWAYS use parentheses
 *     in function-like macros to avoid bugs: `#define NAME(arg) ((arg)...)`.
 * 4.  Conditional compilation (`#ifdef`, `#ifndef`, `#if`, `#else`, `#endif`) lets you
 *     include or exclude code, which is perfect for debugging or platform-specific features.
 *
 * THE MOST IMPORTANT USE OF CONDITIONAL COMPILATION: HEADER GUARDS
 *
 * When you start creating your own `.h` files, you'll run into a "double inclusion"
 * problem. To prevent this, every header file you create MUST be wrapped in
 * a "header guard", which looks like this:
 *
 *   #ifndef MY_UNIQUE_HEADER_NAME_H
 *   #define MY_UNIQUE_HEADER_NAME_H
 *
 *   // All your header file content goes here...
 *
 *   #endif // MY_UNIQUE_HEADER_NAME_H
 *
 * This ensures that even if the file is `#include`d ten times, its content is
 * only processed by the compiler ONCE. We will use this in future lessons.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 22_preprocessor_directives 22_preprocessor_directives.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./22_preprocessor_directives`
 *    - On Windows (WSL): `./22_preprocessor_directives`
 *
 * To see conditional compilation work, try commenting out `#define DEBUG` at the
 * top, then recompile and run. The debug messages will disappear!
 *
 * Alternatively, you can define macros from the command line with the -D flag.
 * Remove `#define DEBUG` from the file, then compile like this:
 * `cc -Wall -Wextra -std=c17 -DDEBUG -o 22_preprocessor_directives 22_preprocessor_directives.c`
 * The debug messages will reappear!
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 22_preprocessor_directives 22_preprocessor_directives.c
./22_preprocessor_directives

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Write a MAX(a, b) macro with every parameter and the whole body in parentheses, and test it with MAX(1 + 2, 3 * 2).
  2. Build the lesson with -DDEBUG and without it, and compare the output.
  3. Call your MAX macro with MAX(x++, y). Why can a macro evaluate an argument twice when a function would not?

Unions and Enums

What you’ll learn: naming constants with enum, sharing memory with union, and the tagged-union pattern that keeps track of which member is valid.

Before you start: Lessons 12 and 22.

Today we’re looking at two special kinds of data types: enum and union. While they look a bit like structs, they solve very different problems.

  • ENUM (Enumeration): Its purpose is to make your code more READABLE and SAFER. An enum creates a set of named integer constants. Instead of using “magic numbers” like 0, 1, 2 to represent states or types, you can use meaningful names like SUCCESS, PENDING, FAILURE.

  • UNION: Its purpose is MEMORY EFFICIENCY. A union allows you to store different data types in the SAME memory location, but only one at a time. While a struct allocates space for ALL its members, a union only allocates enough space for its LARGEST member.

Full Source

/**
 * @file 23_unions_and_enums.c
 * @brief Part 3, Lesson 23: Unions and Enums
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for enums and unions.
 * It explains how these specialized data types are used for creating readable
 * constants and for memory-efficient data storage.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Today we're looking at two special kinds of data types: `enum` and `union`.
 * While they look a bit like `structs`, they solve very different problems.
 *
 * - ENUM (Enumeration):
 *   Its purpose is to make your code more READABLE and SAFER. An `enum` creates a
 *   set of named integer constants. Instead of using "magic numbers" like 0, 1, 2
 *   to represent states or types, you can use meaningful names like `SUCCESS`,
 *   `PENDING`, `FAILURE`.
 *
 * - UNION:
 *   Its purpose is MEMORY EFFICIENCY. A `union` allows you to store different
 *   data types in the SAME memory location, but only one at a time. While a
 *   `struct` allocates space for ALL its members, a `union` only allocates
 *   enough space for its LARGEST member.
 */

#include <stdio.h>
#include <stdint.h> // For fixed-width integers like uint8_t

// --- Part 1: Enums for Readable Code ---
// Let's define an enumeration for different status types in a system.
typedef enum
{
    STATE_PENDING,    // Automatically assigned the value 0
    STATE_PROCESSING, // Automatically assigned the value 1
    STATE_SUCCESS,    // Automatically assigned the value 2
    STATE_FAILURE     // Automatically assigned the value 3
} SystemState;

// --- Part 2: Unions for Memory Efficiency ---
// This union can hold ONE of three types, but not at the same time.
typedef union
{
    int i;
    double d;
    char c;
} DataValue;

// --- Part 3: The Tagged Union - The Best of Both Worlds ---
// A problem with unions is that you don't know WHICH member is currently valid.
// The solution is a TAGGED UNION. We wrap the union in a struct that also
// contains an enum "tag" to tell us what kind of data is currently stored.

typedef enum
{
    TYPE_INT,
    TYPE_DOUBLE,
    TYPE_CHAR
} DataType;

typedef struct
{
    DataType type;   // The tag that tells us what's in the union
    DataValue value; // The union holding the actual data
} TaggedValue;

// --- Function Prototypes (Lesson 7) ---
void print_tagged_value(TaggedValue tv);

// A helper function to print our tagged union safely.
void print_tagged_value(TaggedValue tv)
{
    switch (tv.type)
    {
    case TYPE_INT:
        printf("TaggedValue is an INT: %d\n", tv.value.i);
        break;
    case TYPE_DOUBLE:
        printf("TaggedValue is a DOUBLE: %f\n", tv.value.d);
        break;
    case TYPE_CHAR:
        printf("TaggedValue is a CHAR: '%c'\n", tv.value.c);
        break;
    default:
        printf("TaggedValue has an unknown type.\n");
    }
}

int main(void)
{
    printf("--- Part 1: Using Enums ---\n");
    SystemState current_state = STATE_PROCESSING;

    // The code is much more readable than `if (current_state == 1)`
    if (current_state == STATE_PROCESSING)
    {
        printf("Current system state is: PROCESSING\n\n");
    }

    printf("--- Part 2: Using Unions ---\n");
    DataValue data;

    printf("Size of the DataValue union: %zu bytes\n", sizeof(DataValue));
    printf("Size of a double on this system: %zu bytes\n", sizeof(double));
    printf("The union's size matches its largest member!\n\n");

    // Store an int in the union
    data.i = 123;
    printf("Stored an int: data.i = %d\n", data.i);

    // Now store a double. THIS OVERWRITES THE INT'S MEMORY.
    data.d = 987.654;
    printf("Stored a double: data.d = %f\n", data.d);

    // Reading `data.i` now reads some of the double's bytes as if they were an
    // int. C allows this, but the number is meaningless: the 123 is gone,
    // because the same memory was reused. Which number you get depends on how
    // your machine stores a double and an int, so it can differ between
    // machines (Lesson 37 names this kind of behavior).
    printf("The int value is now garbage: data.i = %d\n\n", data.i);

    printf("--- Part 3: Using Tagged Unions ---\n");

    // Create a tagged value to hold an integer
    TaggedValue int_val;
    int_val.type = TYPE_INT;
    int_val.value.i = 42;
    print_tagged_value(int_val);

    // Create another tagged value to hold a double
    TaggedValue double_val;
    double_val.type = TYPE_DOUBLE;
    double_val.value.d = 3.14159;
    print_tagged_value(double_val);

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  ENUMS create named integer constants to make your code more readable and
 *     less error-prone than using "magic numbers." They are perfect for `switch`
 *     statements or representing a fixed set of states.
 *
 * 2.  UNIONS allow multiple members to share the same memory location. This saves
 *     memory when you know you only need to store one of several possible data
 *     types at any given time.
 *
 * 3.  The most powerful pattern is the TAGGED UNION, where a `struct` contains
 *     both a `union` and an `enum` tag. The tag tells you which field of the
 *     union is currently active, allowing you to use it safely.
 *
 * Understanding when to use these specialized types is a mark of a proficient
 * C programmer.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 23_unions_and_enums 23_unions_and_enums.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./23_unions_and_enums`
 *    - On Windows (WSL): `./23_unions_and_enums`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 23_unions_and_enums 23_unions_and_enums.c
./23_unions_and_enums

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Add STATE_CANCELLED to SystemState and print its value. Which number does it get, and why?
  2. Add a TYPE_BOOL tag and an int is_true member to the tagged union, and print it as true or false in the switch.
  3. Print sizeof of the union and of a struct with the same members. Explain the difference.

Static and Extern Variables

What you’ll learn: controlling a variable’s lifetime and visibility with static and extern.

Before you start: Lessons 7 and 22.

As programs grow, we need more control over our variables and functions. We need to answer two key questions:

  1. LIFETIME: How long does a variable exist in memory?
  2. LINKAGE (VISIBILITY): Which parts of our code are allowed to see it?

The static and extern keywords are our tools for managing this.

static: The “Private” Keyword

The static keyword has two different meanings depending on where you use it, but both are related to making things more “private” or “persistent”:

  • INSIDE A FUNCTION, it controls LIFETIME. A static local variable is created only once and keeps its value between calls, instead of starting over each time the function runs:

    static int count = 0;
    
  • AT FILE SCOPE (on a global variable or a function), it controls LINKAGE. The name becomes private to its own .c file, so other files cannot see it or clash with it:

    static int g_private_variable = 42;
    

extern: The “Public Declaration” Keyword

The extern keyword is used to DECLARE a global variable that is DEFINED in another file. It tells the compiler, “Don’t worry, this variable exists somewhere else. The linker will find it and connect everything.”

Full Source

/**
 * @file 24_static_and_extern_variables.c
 * @brief Part 3, Lesson 24: Static and Extern Variables
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for storage classes,
 * specifically the `static` and `extern` keywords. It explains how these
 * control a variable's lifetime, scope, and linkage across files.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * As programs grow, we need more control over our variables and functions. We need
 * to answer two key questions:
 *
 * 1. LIFETIME: How long does a variable exist in memory?
 * 2. LINKAGE (VISIBILITY): Which parts of our code are allowed to see it?
 *
 * The `static` and `extern` keywords are our tools for managing this.
 *
 * `static` - The "Private" Keyword
 * The `static` keyword has two different meanings depending on where you use it,
 * but both are related to making things more "private" or "persistent".
 *
 * `extern` - The "Public Declaration" Keyword
 * The `extern` keyword is used to DECLARE a global variable that is DEFINED in
 * another file. It tells the compiler, "Don't worry, this variable exists somewhere
 * else. The linker will find it and connect everything."
 */

#include <stdio.h>

// --- Function Prototypes (Lesson 7) ---
// Declaring the functions up front gives a summary of the file. Their
// definitions, with the explanations, follow below.
void regular_counter(void);
void static_counter(void);

// --- Part 1: `static` Inside a Function (Controlling LIFETIME) ---
// When used inside a function, `static` changes a variable's storage duration.
// - A normal (auto) local variable is created on the stack when the function is
//   called and destroyed when the function exits.
// - A `static` local variable is created only once and exists for the ENTIRE
//   lifetime of the program. It RETAINS ITS VALUE between function calls.

void regular_counter(void)
{
    int count = 0; // This variable is recreated and reset to 0 every time.
    count++;
    printf("Regular counter is at: %d\n", count);
}

void static_counter(void)
{
    // This variable is initialized to 0 only the VERY FIRST time.
    // In all subsequent calls, it keeps its previous value.
    static int count = 0;
    count++;
    printf("Static counter is at: %d\n", count);
}

// --- Part 2: `static` at File Scope (Controlling LINKAGE) ---
// When used on a global variable or a function, `static` changes its linkage
// from "external" to "internal".
// - An EXTERNAL linkage variable (the default) can be seen and used by other .c files.
// - An INTERNAL linkage variable is private to this file. No other .c file can see it.
//   This is a key tool for ENCAPSULATION, or hiding implementation details.

int g_public_variable = 100; // EXTERNAL linkage. Visible to other files.

static int g_private_variable = 42; // INTERNAL linkage. Private to this file.

// This also applies to functions.
static void private_helper_function(void)
{
    printf("This is a private helper function. It cannot be called from other files.\n");
}

// --- Part 3: `extern` for Sharing Globals ---
// Imagine we have a variable defined in another file, `globals.c`:
//
//   // In globals.c:
//   int g_shared_counter = 500;
//
// To use `g_shared_counter` in this file, we must DECLARE it with `extern`.
// This tells the compiler that we intend to use it, but the actual variable
// is defined elsewhere. For this single-file example, we will define it at
// the bottom of this file to show how the declaration works.

extern int g_late_defined_variable; // A DECLARATION, not a definition.

int main(void)
{
    printf("--- Part 1: `static` for Variable Lifetime ---\n");
    printf("Calling counters three times:\n");
    regular_counter();
    static_counter();
    printf("---\n");
    regular_counter();
    static_counter();
    printf("---\n");
    regular_counter();
    static_counter();
    printf("\n");

    printf("--- Part 2: `static` for File-Scope Linkage ---\n");
    printf("The public global variable is: %d\n", g_public_variable);
    printf("The private static variable is: %d\n", g_private_variable);
    private_helper_function();
    printf("\n");

    printf("--- Part 3: Using an `extern` Variable ---\n");
    printf("The late-defined variable declared with 'extern' is: %d\n", g_late_defined_variable);

    return 0;
}

// This is the DEFINITION for the `extern` variable declared earlier.
// Because the `main` function has already seen the `extern` declaration, this works.
// In a real project, this definition would be in a separate .c file.
int g_late_defined_variable = 999;

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1. The `static` keyword has two meanings based on context:
 *    - INSIDE a function: Creates a variable that persists for the program's
 *      entire lifetime and retains its value between calls.
 *    - OUTSIDE a function: Creates a global variable or function that is private
 *      to the current file (internal linkage).
 *
 * 2. By default, global variables and functions have EXTERNAL linkage, meaning
 *    they can be shared across multiple .c files.
 *
 * 3. The `extern` keyword is used to DECLARE a global variable that is DEFINED
 *    in another file, allowing you to share variables across your project.
 *
 * These concepts are the bedrock of creating well-structured, multi-file C projects.
 * You use `static` to hide details within a file and `extern` (usually via a header file)
 * to expose the public parts.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 24_static_and_extern_variables 24_static_and_extern_variables.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./24_static_and_extern_variables`
 *    - On Windows (WSL): `./24_static_and_extern_variables`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 24_static_and_extern_variables 24_static_and_extern_variables.c
./24_static_and_extern_variables

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Write a function that returns a new ID each time it is called, using a static counter.
  2. Split the lesson into two .c files that share a global variable through extern, and compile them together.
  3. Try to use the static global from the second file. Read the linker error.

Simple Text Editor

What you’ll learn: a Part 3 capstone: a line editor built on a doubly linked list, with file loading, saving and a command loop.

Before you start: Lessons 13-20.

Welcome to your Part 3 capstone project! This is where we put everything together to build a substantial application: a command-line text editor.

Our editor, which we’ll call sled (Simple Line Editor), will be able to open a file, display its contents, add/delete lines, and save the changes.

The Core Data Structure

The heart of our editor is a DOUBLY-LINKED LIST. This is an enhancement of the linked list from lesson 20. In a doubly-linked list, each node points not only to the NEXT node but also to the PREVIOUS one. This makes operations like inserting and deleting in the middle of the list much more efficient.

Each node in our list will represent one line of text in the file.

Skills Integrated

  • Structs: To define the Line node for our list.
  • Pointers: Extensively used for linking nodes (next, prev) and managing data.
  • Dynamic Memory (malloc/free): To create and destroy lines as needed, plus realloc, new in this lesson, to grow a buffer until a whole line of the file fits.
  • File I/O (fopen, fgets, fprintf): To load and save the file.
  • Command-Line Arguments (argc, argv): To specify which file to edit.
  • Functions: To create a clean, modular, and readable program structure.

Full Source

/**
 * @file 25_simple_text_editor.c
 * @brief Part 3, Capstone Project: Simple Text Editor
 * @author dunamismax
 * @date 06-15-2025
 *
 * This capstone project builds a functional, line-based text editor.
 * It integrates many concepts from the course: doubly-linked lists, dynamic
 * memory allocation, file I/O, command-line arguments, and string manipulation.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Welcome to your Part 3 capstone project! This is where we put everything
 * together to build a substantial application: a command-line text editor.
 *
 * Our editor, which we'll call `sled` (Simple Line Editor), will be able to
 * open a file, display its contents, add/delete lines, and save the changes.
 *
 * THE CORE DATA STRUCTURE:
 * The heart of our editor is a DOUBLY-LINKED LIST. This is an enhancement of the
 * linked list from lesson 20. In a doubly-linked list, each node points not
 * only to the NEXT node but also to the PREVIOUS one. This makes operations like
 * inserting and deleting in the middle of the list much more efficient.
 *
 * Each node in our list will represent one line of text in the file.
 *
 * SKILLS INTEGRATED:
 * - Structs: To define the `Line` node for our list.
 * - Pointers: Extensively used for linking nodes (`next`, `prev`) and managing data.
 * - Dynamic Memory (`malloc`/`free`): To create and destroy lines as needed.
 * - File I/O (`fopen`, `fgets`, `fprintf`): To load and save the file.
 * - Command-Line Arguments (`argc`, `argv`): To specify which file to edit.
 * - Functions: To create a clean, modular, and readable program structure.
 */

#include <errno.h>  // For errno and ERANGE
#include <limits.h> // For INT_MAX
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h> // For a true/false `modified` flag

// --- Data Structures and Global State ---

// The node for our doubly-linked list. Each node is one line of text.
typedef struct Line
{
    char *text;        // Dynamically allocated text of the line
    struct Line *prev; // Pointer to the previous line
    struct Line *next; // Pointer to the next line
} Line;

// Global pointers to the start and end of our list (the "text buffer")
Line *head = NULL;
Line *tail = NULL;
int line_count = 0;
bool modified = false; // Flag to track if the file has been changed

// --- Function Prototypes ---
void load_file(const char *filename);
void save_file(const char *filename);
void free_buffer(void);
void print_lines(void);
void insert_line(int line_number, const char *text);
void delete_line(int line_number);
void append_line(const char *text);
void print_help(void);
bool parse_line_number(const char *text, int *line_number);
void discard_rest_of_line(void);
Line *create_line(const char *text);
char *read_whole_line(FILE *file);

// --- Main Function: The Editor's Control Loop ---

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        return 1;
    }

    char *filename = argv[1];
    load_file(filename);

    char input_buffer[1024];
    printf("Simple Line Editor. Type 'h' for help, 'q' to quit.\n");

    while (true)
    {
        printf("> ");
        if (fgets(input_buffer, sizeof(input_buffer), stdin) == NULL)
        {
            break; // Exit on EOF (Ctrl+D)
        }

        // If there is no newline, the line was too long for the buffer and the
        // rest of it is still waiting in the input. Throw it away, or the next
        // `fgets` would read it and run it as a command.
        if (strchr(input_buffer, '\n') == NULL && !feof(stdin))
        {
            discard_rest_of_line();
            printf("Error: Command too long. Maximum length is %d characters.\n",
                   (int)sizeof(input_buffer) - 2);
            continue;
        }
        input_buffer[strcspn(input_buffer, "\n")] = '\0'; // Remove the newline

        // Parse the command and its argument. The command is the first
        // character, and the argument is everything after the space that
        // follows it ("a Some text" -> 'a' and "Some text").
        //
        // CAREFUL: a command like "p" has no argument. `input_buffer + 2` would
        // then point past the end of the text, at bytes `fgets` never wrote.
        // So `argument` starts as an empty string: it points at the `\0` that
        // ends the text.
        char command = input_buffer[0];
        char *argument = input_buffer + strlen(input_buffer);

        if (command == '\0')
        {
            continue; // An empty line: just show the prompt again.
        }
        if (input_buffer[1] == ' ')
        {
            argument = input_buffer + 2;
        }
        else if (input_buffer[1] != '\0')
        {
            command = '?'; // Something like "pq" is not one of our commands.
        }

        int line_num = 0;
        switch (command)
        {
        case 'p':
            print_lines();
            break;
        case 'a': // Append
            append_line(argument);
            break;
        case 'i': // Insert
        {
            char *text_start = strchr(argument, ' ');
            if (text_start)
            {
                *text_start = '\0'; // Split line number from text
                text_start++;
                if (parse_line_number(argument, &line_num))
                {
                    insert_line(line_num, text_start);
                }
            }
            else
            {
                printf("Usage: i <line_number> <text>\n");
            }
            break;
        }
        case 'd': // Delete
            if (parse_line_number(argument, &line_num))
            {
                delete_line(line_num);
            }
            break;
        case 's':
            save_file(filename);
            break;
        case 'h':
            print_help();
            break;
        case 'q':
            if (modified)
            {
                printf("File has unsaved changes. Save first? (y/n): ");
                if (fgets(input_buffer, sizeof(input_buffer), stdin) != NULL &&
                    (input_buffer[0] == 'y' || input_buffer[0] == 'Y'))
                {
                    save_file(filename);
                }
            }
            printf("Exiting.\n");
            free_buffer();
            return 0;
        default:
            printf("Unknown command. Type 'h' for help.\n");
        }
    }

    free_buffer();
    return 0;
}

// --- Function Implementations ---

/**
 * @brief Reads and throws away the rest of the current input line.
 */
void discard_rest_of_line(void)
{
    int ch;
    while ((ch = getchar()) != '\n' && ch != EOF)
    {
        // Keep reading until the end of the line (or of the input).
    }
}

/**
 * @brief Converts a line number typed by the user, such as "3", to an int.
 * @return true on success. On failure it prints why and returns false.
 *
 * We use `strtol` (Lesson 15) rather than `atoi`, which would turn "abc" into
 * 0 and "2x" into 2 without telling us anything was wrong.
 */
bool parse_line_number(const char *text, int *line_number)
{
    char *end = NULL;
    long value;

    // A number too big for a `long` comes back as LONG_MAX with `errno` set
    // to ERANGE. Testing `value > INT_MAX` is not enough on its own: where
    // `long` and `int` are the same size (32-bit systems), LONG_MAX equals
    // INT_MAX and would pass. `errno` must be cleared first, because no
    // function ever sets it back to 0.
    errno = 0;
    value = strtol(text, &end, 10);

    if (end == text || *end != '\0' || errno == ERANGE || value < 1 || value > INT_MAX)
    {
        printf("Error: '%s' is not a valid line number.\n", text);
        return false;
    }

    *line_number = (int)value;
    return true;
}

/**
 * @brief Prints the help menu.
 */
void print_help(void)
{
    printf("--- sled Help ---\n");
    printf("p              - Print all lines\n");
    printf("a <text>       - Append a new line of text to the end\n");
    printf("i <num> <text> - Insert text before line <num>\n");
    printf("d <num>        - Delete line <num>\n");
    printf("s              - Save the file\n");
    printf("h              - Show this help message\n");
    printf("q              - Quit the editor\n");
}

/**
 * @brief Allocates a new line node.
 */
Line *create_line(const char *text)
{
    Line *new_line = (Line *)malloc(sizeof(Line));
    if (!new_line)
    {
        perror("malloc failed for new line");
        exit(1);
    }
    // Allocate space for the text and copy it over. `strcpy` does not check
    // sizes, but here the destination is exactly big enough: `strlen(text)`
    // characters plus one for the `\0`.
    new_line->text = malloc(strlen(text) + 1);
    if (!new_line->text)
    {
        perror("malloc failed for line text");
        exit(1);
    }
    strcpy(new_line->text, text);
    new_line->prev = NULL;
    new_line->next = NULL;
    return new_line;
}

/**
 * @brief Appends a new line to the end of the text buffer.
 */
void append_line(const char *text)
{
    Line *new_line = create_line(text);
    if (tail == NULL)
    { // List is empty
        head = tail = new_line;
    }
    else
    {
        tail->next = new_line;
        new_line->prev = tail;
        tail = new_line;
    }
    line_count++;
    modified = true;
}

/**
 * @brief Loads the content of a file into the linked-list buffer.
 */
void load_file(const char *filename)
{
    FILE *file = fopen(filename, "r");
    if (file == NULL)
    {
        printf("New file: '%s'\n", filename);
        return; // It's okay if the file doesn't exist yet
    }

    // A line in a file can be any length, so a fixed `char buffer[1024]` and
    // `fgets` would split a longer line into several pieces, and saving would
    // then change the file. `read_whole_line` grows its buffer instead.
    char *text = NULL;
    while ((text = read_whole_line(file)) != NULL)
    {
        append_line(text);
        free(text); // `append_line` stored its own copy.
    }
    if (ferror(file))
    {
        printf("Warning: could not read all of '%s'.\n", filename);
    }
    fclose(file);
    modified = false; // Freshly loaded, so not modified yet
}

/**
 * @brief Reads one whole line from a file, however long it is.
 *
 * Returns the line without its newline, in memory from `malloc` that the
 * caller must `free`, or NULL when there is nothing left to read.
 */
char *read_whole_line(FILE *file)
{
    size_t capacity = 128;
    size_t length = 0;
    char *line = malloc(capacity);
    if (line == NULL)
    {
        perror("malloc failed while reading the file");
        exit(1);
    }

    int c = fgetc(file);
    if (c == EOF)
    {
        free(line);
        return NULL; // No more lines.
    }

    while (c != EOF && c != '\n')
    {
        // Keep one byte free for the `\0`. When the buffer is full, double it.
        //
        // REALLOC asks for a bigger block and copies the old contents into it.
        // The new block may be at a different address. If it fails, it returns
        // NULL and leaves the old block alone, so we store its result in a
        // separate pointer: writing `line = realloc(line, ...)` would lose our
        // only pointer to the old block, and leak it, on failure.
        if (length + 1 == capacity)
        {
            char *bigger = realloc(line, capacity * 2);
            if (bigger == NULL)
            {
                free(line);
                perror("realloc failed while reading the file");
                exit(1);
            }
            line = bigger;
            capacity *= 2;
        }
        // `c` is not EOF here, so it holds a character value that fits in a
        // `char`; the cast says so.
        line[length] = (char)c;
        length++;
        c = fgetc(file);
    }

    line[length] = '\0';
    return line;
}

/**
 * @brief Saves the current buffer content to the file.
 */
void save_file(const char *filename)
{
    FILE *file = fopen(filename, "w");
    if (file == NULL)
    {
        perror("Could not open file for writing");
        return;
    }

    Line *current = head;
    while (current != NULL)
    {
        fprintf(file, "%s\n", current->text);
        current = current->next;
    }

    // Writes are buffered, so an error such as a full disk may only appear
    // when `fclose` writes the last of them. `ferror` tells us whether any
    // earlier write failed. If anything went wrong we keep `modified` set,
    // so quitting still warns about unsaved changes.
    bool write_failed = ferror(file) != 0;
    if (fclose(file) != 0 || write_failed)
    {
        printf("Error: Could not save '%s'. Your changes are NOT saved.\n", filename);
        return;
    }
    printf("File '%s' saved.\n", filename);
    modified = false;
}

/**
 * @brief Frees all memory used by the text buffer.
 */
void free_buffer(void)
{
    Line *current = head;
    while (current != NULL)
    {
        Line *next = current->next;
        free(current->text); // Free the text string first
        free(current);       // Then free the node itself
        current = next;
    }
    head = tail = NULL;
    line_count = 0;
}

/**
 * @brief Prints all lines with line numbers.
 */
void print_lines(void)
{
    Line *current = head;
    int i = 1;
    while (current != NULL)
    {
        printf("%4d: %s\n", i++, current->text);
        current = current->next;
    }
}

/**
 * @brief Inserts a line at a specific position.
 */
void insert_line(int line_number, const char *text)
{
    if (line_number < 1 || line_number > line_count + 1)
    {
        printf("Error: Invalid line number.\n");
        return;
    }
    if (line_number == line_count + 1)
    {
        append_line(text);
        return;
    }

    Line *new_line = create_line(text);
    Line *current = head;
    for (int i = 1; i < line_number; i++)
    {
        current = current->next;
    }

    // Re-wire the pointers
    new_line->next = current;
    new_line->prev = current->prev;

    if (current->prev == NULL)
    { // Inserting at the head
        head = new_line;
    }
    else
    {
        current->prev->next = new_line;
    }
    current->prev = new_line;

    line_count++;
    modified = true;
}

/**
 * @brief Deletes a line at a specific position.
 */
void delete_line(int line_number)
{
    if (line_number < 1 || line_number > line_count)
    {
        printf("Error: Invalid line number.\n");
        return;
    }

    Line *to_delete = head;
    for (int i = 1; i < line_number; i++)
    {
        to_delete = to_delete->next;
    }

    // Bypass the node to be deleted
    if (to_delete->prev)
        to_delete->prev->next = to_delete->next;
    else
        head = to_delete->next; // Deleting the head

    if (to_delete->next)
        to_delete->next->prev = to_delete->prev;
    else
        tail = to_delete->prev; // Deleting the tail

    free(to_delete->text);
    free(to_delete);
    line_count--;
    modified = true;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Congratulations! You have built a complex, useful application from the ground up.
 * This project required careful management of memory, pointers, and program state,
 * exercising nearly every major C concept we have learned.
 *
 * Key Project Achievements:
 * - A DOUBLY-LINKED LIST implementation for efficient line editing.
 * - Robust FILE I/O for data persistence.
 * - A clean COMMAND-LINE INTERFACE for user interaction.
 * - Careful DYNAMIC MEMORY MANAGEMENT to prevent leaks.
 * - A modular structure that separates concerns into different functions.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 25_simple_text_editor 25_simple_text_editor.c`
 *
 * 4. Run the executable with a file name:
 *    - On Linux/macOS:   `./25_simple_text_editor my_document.txt`
 *    - On Windows (WSL): `./25_simple_text_editor my_document.txt`
 *
 * Once inside, try the commands:
 * > a This is the first line.
 * > a This is the second.
 * > p
 * > i 2 This line goes in the middle.
 * > p
 * > d 1
 * > p
 * > s
 * > q
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 25_simple_text_editor 25_simple_text_editor.c
./25_simple_text_editor my_document.txt

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Add an n command that prints the number of lines.
  2. Add an f TEXT command that prints every line containing TEXT, using strstr.
  3. Add an r N TEXT command that replaces line N with TEXT, freeing the old text.

Simple Socket Server and Client

What you’ll learn: TCP networking with sockets: a server that binds, listens and accepts, and a client that connects, sends and receives.

Before you start: Parts 1-3. The lesson uses POSIX, so on Windows run it in WSL.

The Client

Welcome to the world of network programming! In this lesson, we will build a complete, working client-server application in two programs: a CLIENT and a SERVER. This is your gateway to understanding how programs communicate over the internet.

The Client-Server Model

Most network communication follows a CLIENT-SERVER model.

  • A SERVER is a program that runs continuously, LISTENS for incoming connections on a specific port, and provides a service.
  • A CLIENT is a program that actively initiates a connection to a server to request that service.

Think of a web browser (client) connecting to a web server (like google.com) to request a webpage. This file is the CLIENT.

What Is a Socket?

A SOCKET is an endpoint for communication between two programs over a network. You can think of it like a telephone for your program. You create a socket, ‘dial’ the server’s address and port, and then you can send and receive data through it.

We will be using TCP/IP sockets (specifically, AF_INET and SOCK_STREAM), which provide a reliable, connection-oriented communication channel. This means data arrives in order and without errors, like a phone call.

The Client’s Journey

A typical client program follows these steps:

  1. Create a SOCKET.
  2. Specify the server’s IP address and PORT number.
  3. CONNECT to the server.
  4. SEND data (a message).
  5. RECEIVE a response.
  6. CLOSE the connection.

Let’s build it!

The socket() function creates a communication endpoint and returns a file descriptor for it.

Arguments:

  1. domain: AF_INET specifies the IPv4 protocol family.
  2. type: SOCK_STREAM specifies a TCP socket (reliable, connection-oriented).
  3. protocol: 0 tells the OS to choose the proper protocol (TCP for SOCK_STREAM).

struct sockaddr_in is a structure used to store addresses for the AF_INET family.

  • sin_family: The address family. Must match the one used in socket().
  • sin_port: The port number. We must use htons() (Host TO Network Short) to convert the port number into NETWORK BYTE ORDER. This ensures that computers with different byte ordering can communicate correctly.
  • sin_addr: The IP address. inet_pton() (“presentation to network”) converts the string IP (e.g., “127.0.0.1”) into the binary format the network uses. It returns 1 on success and 0 if the string is not a valid IPv4 address, so the client can report a typo instead of connecting to the wrong place. (Older code uses inet_addr(), which cannot tell an error apart from the real address 255.255.255.255.)

The client fills the whole struct with zeros using memset first, so the fields it never sets do not hold leftover garbage. It also checks the port with strtol, exactly as the server does.

The connect() function establishes a connection to the server. It’s a BLOCKING call; it will wait until the connection is made or an error occurs.

Arguments:

  1. The client’s socket descriptor.
  2. A pointer to the server’s address struct. Note the cast to (struct sockaddr *). This is a C convention for generic socket functions.
  3. The size of the address structure.

The send() function transmits data to the connected socket. It returns the number of bytes sent, or -1 on error.

The recv() function receives data from a socket. It’s a BLOCKING call; the program will pause here until data arrives. It returns the number of bytes received, 0 if the connection was closed, or -1 on error.

The bytes that arrive have no \0 at the end. Both programs ask recv for at most one byte less than the size of a zeroed buffer (sizeof(server_reply) - 1 in the client, sizeof(client_message) - 1 in the server), so the last byte always stays \0 and the message is a proper string for %s.

TCP delivers a STREAM of bytes, not separate messages, so one recv may return only part of what was sent. A short message between two programs on one machine almost always arrives in one piece, which is enough for this lesson. Real protocols mark where a message ends and call recv in a loop.

Client Source

/**
 * @file 26_simple_socket_client.c
 * @brief Part 4, Lesson 26: Simple Socket Client
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file implements the client side of our basic TCP client-server application.
 * This program will connect to a running server, send it a message, and
 * print the server's response to the console.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Welcome to the world of network programming! In this lesson, we will build a
 * complete, working client-server application in two programs: this CLIENT and
 * a SERVER (`26_simple_socket_server.c`). This is your gateway to understanding
 * how programs communicate over the internet.
 *
 * THE CLIENT-SERVER MODEL
 * Most network communication follows a CLIENT-SERVER model.
 * - A SERVER is a program that runs continuously, LISTENS for incoming
 *   connections on a specific port, and provides a service.
 * - A CLIENT is a program that actively initiates a connection to a server to
 *   request that service.
 *
 * Think of a web browser (client) connecting to a web server (like google.com)
 * to request a webpage. This file is the CLIENT.
 *
 * WHAT IS A SOCKET?
 * A SOCKET is an endpoint for communication between two programs over a network.
 * You can think of it like a telephone for your program. You create a socket,
 * 'dial' the server's address and port, and then you can send and receive
 * data through it.
 *
 * We will be using TCP/IP sockets (specifically, AF_INET and SOCK_STREAM), which
 * provide a reliable, connection-oriented communication channel. This means data
 * arrives in order and without errors, like a phone call.
 *
 * THE CLIENT'S JOURNEY
 * A typical client program follows these steps:
 * 1. Create a SOCKET.
 * 2. Specify the server's IP address and PORT number.
 * 3. CONNECT to the server.
 * 4. SEND data (a message).
 * 5. RECEIVE a response.
 * 6. CLOSE the connection.
 *
 * Let's build it!
 */

// --- Required Headers ---
// We need several headers for network programming.
#include <errno.h>      // For errno, which strtol() sets on overflow
#include <stdio.h>      // For standard I/O, like printf() and perror()
#include <stdlib.h>     // For exit() and strtol()
#include <string.h>     // For string manipulation, like strlen() and memset()
#include <unistd.h>     // For close()
#include <sys/socket.h> // The main header for socket programming functions
#include <arpa/inet.h>  // For functions like inet_pton() and htons()

// This is the function signature we use when we want to accept command-line arguments.
int main(int argc, char *argv[])
{
    // --- Step 0: Validate Command-Line Arguments ---
    // Our client needs to know where the server is and what message to send.
    // We expect: ./program_name <SERVER_IP> <PORT> <MESSAGE>
    if (argc != 4)
    {
        // `fprintf` is like `printf`, but it lets us specify the output stream.
        // `stderr` is the "standard error" stream, the conventional place for errors.
        fprintf(stderr, "Usage: %s <Server IP> <Port> <Message>\n", argv[0]);
        return 1; // Exit with a non-zero status to indicate an error.
    }

    // Parse the arguments from the command line.
    char *server_ip = argv[1];
    char *message = argv[3];

    // The port arrives as a string. We convert it with `strtol` and check it,
    // exactly as the server does: `atoi` would turn a typo such as "88a8" into
    // 88 and silently connect to the wrong port.
    char *endptr = NULL;
    errno = 0;
    long parsed_port = strtol(argv[2], &endptr, 10);
    if (errno != 0 || endptr == argv[2] || *endptr != '\0' || parsed_port < 1 || parsed_port > 65535)
    {
        fprintf(stderr, "Error: Port must be a whole number between 1 and 65535.\n");
        return 1;
    }
    int port = (int)parsed_port;

    // --- Part 1: Create a Socket ---

    // A SOCKET DESCRIPTOR is an integer that uniquely identifies a socket, much like
    // a FILE DESCRIPTOR identifies an open file.
    int client_socket;

    /*
     * The `socket()` function creates a communication endpoint and returns a
     * file descriptor for it.
     *
     * ARGUMENTS:
     * 1. domain: AF_INET specifies the IPv4 protocol family.
     * 2. type:   SOCK_STREAM specifies a TCP socket (reliable, connection-oriented).
     * 3. protocol: 0 tells the OS to choose the proper protocol (TCP for SOCK_STREAM).
     */
    printf("Creating client socket...\n");
    client_socket = socket(AF_INET, SOCK_STREAM, 0);

    // `socket()` returns -1 on failure. `perror` prints a descriptive system error.
    if (client_socket == -1)
    {
        perror("Could not create socket");
        return 1;
    }
    printf("Socket created.\n");

    // --- Part 2: Configure Server Address ---

    // We need a structure to hold the server's address information.
    // `memset` fills it with zeros first. The struct has fields we never set
    // ourselves (padding, and on some systems a length field), and they must
    // not hold leftover garbage.
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));

    /*
     * `struct sockaddr_in` is a structure used to store addresses for the AF_INET family.
     *
     * - sin_family: The address family. Must match the one used in `socket()`.
     * - sin_port: The port number. We must use `htons()` (Host TO Network Short)
     *   to convert the port number into NETWORK BYTE ORDER. This ensures that
     *   computers with different byte ordering can communicate correctly.
     * - sin_addr: The IP address. `inet_pton()` ("presentation to network")
     *   converts the string IP (e.g., "127.0.0.1") into the binary format the
     *   network uses. It returns 1 on success and 0 if the string is not a
     *   valid IPv4 address, so we can report a typo instead of connecting to
     *   the wrong place. (Older code uses `inet_addr()`, which cannot tell an
     *   error apart from the real address 255.255.255.255.)
     */
    server_addr.sin_family = AF_INET;
    // `htons` takes a 16-bit unsigned value (`uint16_t`). We checked above
    // that the port is 1-65535, so the cast keeps every possible port intact.
    server_addr.sin_port = htons((uint16_t)port);
    if (inet_pton(AF_INET, server_ip, &server_addr.sin_addr) != 1)
    {
        fprintf(stderr, "Error: '%s' is not a valid IPv4 address.\n", server_ip);
        close(client_socket);
        return 1;
    }

    // --- Part 3: Connect to the Server ---

    /*
     * The `connect()` function establishes a connection to the server.
     * It's a BLOCKING call; it will wait until the connection is made or an
     * error occurs.
     *
     * ARGUMENTS:
     * 1. The client's socket descriptor.
     * 2. A pointer to the server's address struct. Note the cast to
     *    `(struct sockaddr *)`. This is a C convention for generic socket functions.
     * 3. The size of the address structure.
     */
    printf("Connecting to server at %s:%d...\n", server_ip, port);
    if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
    {
        perror("Connection failed");
        close(client_socket);
        return 1;
    }
    printf("Connected to server.\n");

    // --- Part 4: Send and Receive Data ---

    // Now that we're connected, we can send our message.
    /*
     * The `send()` function transmits data to the connected socket.
     * It returns the number of bytes sent, or -1 on error.
     */
    printf("Sending message: \"%s\"\n", message);
    if (send(client_socket, message, strlen(message), 0) < 0)
    {
        perror("Send failed");
        close(client_socket);
        return 1;
    }

    // Now we wait for the server's reply.
    char server_reply[2000];
    ssize_t recv_size; // `ssize_t` is a signed size type, so it can hold -1.

    // It's good practice to clear the buffer before receiving data into it.
    memset(server_reply, 0, sizeof(server_reply));

    /*
     * The `recv()` function receives data from a socket.
     * It's a BLOCKING call; the program will pause here until data arrives.
     * It returns the number of bytes received, 0 if the connection was closed,
     * or -1 on error.
     *
     * The data we receive is just bytes, with no `\0` at the end. We ask for at
     * most `sizeof(server_reply) - 1` bytes, so the last byte of the buffer is
     * always one of the zeros from `memset`. That guarantees the reply is a
     * proper string when we print it with `%s`, even if the server sends
     * 2000 bytes or more.
     */
    recv_size = recv(client_socket, server_reply, sizeof(server_reply) - 1, 0);
    if (recv_size < 0)
    {
        perror("Receive failed");
        close(client_socket);
        return 1;
    }

    printf("Server reply: %s\n", server_reply);

    // --- Part 5: Close the Socket ---

    // Always clean up! Closing the socket releases the resources.
    close(client_socket);
    printf("Connection closed.\n");

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * This is the CLIENT part of a two-part application. You must compile and run
 * the server first.
 *
 * 1. Open a terminal and compile the client:
 *    `cc -Wall -Wextra -std=c17 -o 26_simple_socket_client 26_simple_socket_client.c`
 *
 * 2. In a DIFFERENT terminal, compile and run the server (`26_simple_socket_server.c`):
 *    `cc -Wall -Wextra -std=c17 -o 26_simple_socket_server 26_simple_socket_server.c`
 *    `./26_simple_socket_server 8888`
 *
 * 3. Go back to the FIRST terminal (for the client) and run it, providing the
 *    server's IP, port, and a message. If the server is on the same machine,
 *    the IP is 127.0.0.1 (localhost).
 *
 *    `./26_simple_socket_client 127.0.0.1 8888 "Hello from the C client!"`
 *
 *    You should see the client connect, send the message, and then print the
 *    server's reply. The server's terminal will show the message it received.
 */

The Server

This is the SERVER component of our application. A server’s primary role is to listen for and accept connections from clients.

While the client actively initiates contact, the server is passive. It sets up a ‘shop’ at a known address (IP and PORT) and waits for customers (clients) to arrive.

The Server’s Journey

A typical TCP server program follows these steps, which are different from the client’s:

  1. Create a SOCKET. (Same as the client)
  2. BIND the socket to a specific IP address and port number. This is how clients will find it.
  3. LISTEN on that port for incoming connection requests. This puts the socket into a “listening state.”
  4. ACCEPT a connection from a client. This creates a NEW socket dedicated to communicating with that specific client. The original socket remains listening for other clients.
  5. RECEIVE and SEND data with the connected client using the new socket.
  6. CLOSE the client’s connection and, eventually, the main listening socket.

Key server-specific functions are bind(), listen(), and accept().

Before binding, the server turns on SO_REUSEADDR with setsockopt(). After a connection closes, the operating system keeps its port reserved for a minute or two (the TIME_WAIT state). Without the option, stopping the server and starting it again straight away fails with “Address already in use”:

int reuse = 1;
if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)

INADDR_ANY is a special constant that tells the socket to bind to all available network interfaces on the machine (e.g., Wi-Fi, Ethernet, etc.). This is the standard way to configure a server so it can accept connections from both the local machine (127.0.0.1) and from other machines on the network.

The bind() function assigns the address specified by server_addr to the socket descriptor server_socket. This is a critical step for a server.

The listen() function puts the server socket into a passive mode, where it waits for the client to approach the server to make a connection. The second argument (3) is the BACKLOG, which is the maximum number of pending connections that can be queued up before the server starts refusing new ones.

The accept() function is a BLOCKING call. The program will pause here and wait until a client connects. When a connection is accepted, it creates a NEW SOCKET descriptor (client_socket) for this specific communication channel. The original server_socket remains open and listening for more connections. It also fills the client_addr struct with the client’s information.

To print who connected, the server turns that address back into text with inet_ntop() (“network to presentation”), the reverse of the client’s inet_pton(). It writes into a buffer of INET_ADDRSTRLEN bytes that the server provides. (Older code uses inet_ntoa(), which only knows IPv4 and returns one shared buffer that the next call overwrites.)

Server Source

/**
 * @file 26_simple_socket_server.c
 * @brief Part 4, Lesson 26: Simple Socket Server
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file implements the server side of our basic TCP client-server application.
 * This program will wait for a client to connect, receive a message,
 * send a reply, and then shut down.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * This is the SERVER component of our application. A server's primary role is
 * to listen for and accept connections from clients.
 *
 * While the client actively initiates contact, the server is passive. It sets
 * up a 'shop' at a known address (IP and PORT) and waits for customers (clients)
 * to arrive.
 *
 * THE SERVER'S JOURNEY
 * A typical TCP server program follows these steps, which are different from
 * the client's:
 *
 * 1. Create a SOCKET. (Same as the client)
 * 2. BIND the socket to a specific IP address and port number. This is how clients
 *    will find it.
 * 3. LISTEN on that port for incoming connection requests. This puts the socket
 *    into a "listening state."
 * 4. ACCEPT a connection from a client. This creates a NEW socket dedicated to
 *    communicating with that specific client. The original socket remains
 *    listening for other clients.
 * 5. RECEIVE and SEND data with the connected client using the new socket.
 * 6. CLOSE the client's connection and, eventually, the main listening socket.
 *
 * Key server-specific functions are `bind()`, `listen()`, and `accept()`.
 */

// --- Required Headers ---
#include <arpa/inet.h>  // For address structures and functions
#include <errno.h>      // For errno during numeric parsing
#include <stdio.h>      // For standard I/O
#include <stdlib.h>     // For exit() and strtol()
#include <string.h>     // For string manipulation
#include <sys/socket.h> // The main header for socket programming
#include <unistd.h>     // For close(), write()

int main(int argc, char *argv[])
{
    // --- Step 0: Validate Command-Line Arguments ---
    // The server needs to know which port to listen on.
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s <Port>\n", argv[0]);
        return 1;
    }

    char *endptr = NULL;
    errno = 0;
    long parsed_port = strtol(argv[1], &endptr, 10);
    if (errno != 0 || endptr == argv[1] || *endptr != '\0' || parsed_port < 1 || parsed_port > 65535)
    {
        fprintf(stderr, "Error: Port must be a whole number between 1 and 65535.\n");
        return 1;
    }
    int port = (int)parsed_port;

    // --- Part 1: Create the Server Socket ---

    int server_socket, client_socket;

    // Create the socket. Same as the client.
    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1)
    {
        perror("Could not create server socket");
        return 1;
    }
    printf("Server socket created.\n");

    /*
     * SO_REUSEADDR lets `bind()` take the port again straight away. After a
     * connection closes, the operating system keeps its port reserved for a
     * minute or two (the TIME_WAIT state) so that late packets from it are not
     * mistaken for a new connection. Without this option, stopping the server
     * and starting it again at once fails with "Address already in use".
     * `setsockopt` sets an option on a socket; this one is an `int` flag, and
     * 1 turns it on. It must be set before `bind()`.
     */
    int reuse = 1;
    if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
    {
        perror("Could not set SO_REUSEADDR");
        close(server_socket);
        return 1;
    }

    // --- Part 2: Bind the Socket to an IP and Port ---

    struct sockaddr_in server_addr, client_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    memset(&client_addr, 0, sizeof(client_addr));

    // Prepare the sockaddr_in structure for the server.
    server_addr.sin_family = AF_INET;
    // The port to listen on. `htons` takes a 16-bit unsigned value, and the
    // check above guarantees the port fits in one.
    server_addr.sin_port = htons((uint16_t)port);

    /*
     * INADDR_ANY is a special constant that tells the socket to bind to all
     * available network interfaces on the machine (e.g., Wi-Fi, Ethernet, etc.).
     * This is the standard way to configure a server so it can accept connections
     * from both the local machine (127.0.0.1) and from other machines on the
     * network.
     */
    server_addr.sin_addr.s_addr = INADDR_ANY;

    /*
     * The `bind()` function assigns the address specified by `server_addr` to
     * the socket descriptor `server_socket`. This is a critical step for a server.
     */
    printf("Binding socket to port %d...\n", port);
    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
    {
        perror("Bind failed");
        close(server_socket);
        return 1;
    }
    printf("Bind successful.\n");

    // --- Part 3: Listen for Connections ---

    /*
     * The `listen()` function puts the server socket into a passive mode, where
     * it waits for the client to approach the server to make a connection.
     * The second argument (3) is the BACKLOG, which is the maximum number of
     * pending connections that can be queued up before the server starts
     * refusing new ones.
     */
    if (listen(server_socket, 3) < 0)
    {
        perror("Listen failed");
        close(server_socket);
        return 1;
    }
    printf("Server listening on port %d...\n", port);
    printf("Waiting for incoming connections...\n");

    // --- Part 4: Accept Incoming Connections ---

    socklen_t client_addr_size = sizeof(client_addr);

    /*
     * The `accept()` function is a BLOCKING call. The program will pause here
     * and wait until a client connects.
     * When a connection is accepted, it creates a NEW SOCKET descriptor
     * (`client_socket`) for this specific communication channel.
     * The original `server_socket` remains open and listening for more connections.
     * It also fills the `client_addr` struct with the client's information.
     */
    client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_size);

    if (client_socket < 0)
    {
        perror("Accept failed");
        close(server_socket);
        return 1;
    }

    /*
     * `inet_ntop` ("network to presentation") is the reverse of the client's
     * `inet_pton`: it writes the client's address as text, such as
     * "127.0.0.1", into a buffer we provide. INET_ADDRSTRLEN is the size an
     * IPv4 address needs, `\0` included. Older code uses `inet_ntoa`, which
     * only knows IPv4 and returns one shared buffer that its next call
     * overwrites; `inet_ntop` has neither problem. It returns NULL on failure.
     */
    char client_ip[INET_ADDRSTRLEN];
    const char *shown_ip = inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, sizeof(client_ip));
    printf("Connection accepted from %s:%d\n", shown_ip != NULL ? shown_ip : "an unknown address",
           ntohs(client_addr.sin_port));

    // --- Part 5: Communicate with the Client ---

    char client_message[2000];
    ssize_t read_size; // `ssize_t` is a signed size type, so it can hold -1.

    // Clear the buffer before reading into it.
    memset(client_message, 0, sizeof(client_message));

    /*
     * Receive a message from the client using the NEW socket descriptor.
     * `recv` is also a BLOCKING call.
     *
     * The bytes that arrive have no `\0` at the end. We ask for at most
     * `sizeof(client_message) - 1` bytes, so the last byte always stays one of
     * the zeros from `memset` and the message is a proper string for `%s`.
     *
     * NOTE: TCP delivers a STREAM of bytes, not separate messages. One `recv`
     * may return only part of what the client sent. A short message between
     * two programs on one machine almost always arrives in one piece, which is
     * enough for this lesson. Real protocols mark where a message ends (with a
     * newline or a length) and call `recv` in a loop until it is complete.
     */
    read_size = recv(client_socket, client_message, sizeof(client_message) - 1, 0);
    if (read_size > 0)
    {
        printf("Client message: %s\n", client_message);

        // Prepare and send a reply back to the client.
        const char *reply_message = "Message received. Thank you!";
        // `write()` is another function for sending data, similar to `send()`.
        // Like `send()`, it returns -1 if it fails.
        if (write(client_socket, reply_message, strlen(reply_message)) < 0)
        {
            perror("Write failed");
        }
        else
        {
            printf("Reply sent to client.\n");
        }
    }
    else if (read_size == 0)
    {
        printf("Client disconnected.\n");
    }
    else
    {
        perror("Receive failed");
    }

    // --- Part 6: Close the Sockets ---

    // This simple server handles one client and then shuts down.
    // A real-world server would loop back to `accept()` to handle more clients.
    // We must close BOTH the client-specific socket and the main server socket.
    close(client_socket);
    close(server_socket);
    printf("Sockets closed. Server shutting down.\n");

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * This is the SERVER. It must be running BEFORE you run the client.
 *
 * 1. Open a terminal and compile the server:
 *    `cc -Wall -Wextra -std=c17 -o 26_simple_socket_server 26_simple_socket_server.c`
 *
 * 2. Run the server, providing a port number for it to listen on.
 *    A common choice for testing is a high-numbered port like 8888.
 *    `./26_simple_socket_server 8888`
 *
 *    The server will start and print "Waiting for incoming connections...".
 *    It is now paused, waiting for a client.
 *
 * 3. Open a SECOND terminal and run the compiled client program as described
 *    in the client's source file.
 *
 *    `./26_simple_socket_client 127.0.0.1 8888 "This is a test!"`
 *
 *    You will see the output in both terminals as they communicate.
 */

How to Compile and Run

Build both programs:

cc -Wall -Wextra -std=c17 -o 26_simple_socket_server 26_simple_socket_server.c
cc -Wall -Wextra -std=c17 -o 26_simple_socket_client 26_simple_socket_client.c

Run the server in one terminal:

./26_simple_socket_server 8888

Connect with the client in another terminal, giving the server’s address, its port and a message:

./26_simple_socket_client 127.0.0.1 8888 "Hello from the C client!"

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Make the server reply with the message in uppercase.
  2. Make the server handle clients one after another in a loop instead of exiting after one.
  3. Run the client with a port where no server is listening, and check the error message.

Build Your Own grep

What you’ll learn: a project that rebuilds the core of grep: arguments, reading a file line by line, and searching with strstr.

Before you start: Lessons 14 and 15.

This lesson is a project: your own version of a classic Unix tool.

grep (which stands for Global Regular Expression Print) is one of the most famous and widely used command-line utilities in the Unix world. Its job is to search for a specific pattern of text inside files and print the lines that contain a match.

Our goal is to build a simplified version of grep. It won’t support complex regular expressions, but it will search for a fixed string within a file and print any matching lines. This is a fantastic project because it combines:

  1. COMMAND-LINE ARGUMENTS: To get the search pattern and the filename from the user.
  2. FILE I/O: To open and read the target file.
  3. STRING MANIPULATION: To search for the pattern within each line of the file.
  4. ERROR HANDLING: To manage cases where the user provides wrong input or the file doesn’t exist.

The Plan

  1. Get two arguments from the command line: the search pattern and the filename.
  2. Open the filename for reading.
  3. Read the file one line at a time.
  4. For each line, check if it contains the pattern.
  5. If it does, print that line to the console.
  6. Close the file and exit.

Let’s get started!

Full Source

/**
 * @file 27_build_your_own_grep.c
 * @brief Part 4, Lesson 27: Build Your Own grep
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file is a project that combines many of our previously learned skills
 * to build a simplified version of the famous `grep` command-line utility.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * PROJECT: BUILD YOUR OWN `grep`
 *
 * `grep` (which stands for Global Regular Expression Print) is one of the most
 * famous and widely used command-line utilities in the Unix world. Its job is
 * to search for a specific pattern of text inside files and print the lines
 * that contain a match.
 *
 * Our goal is to build a simplified version of `grep`. It won't support complex
 * regular expressions, but it will search for a fixed string within a file and
 * print any matching lines. This is a fantastic project because it combines:
 *
 * 1. COMMAND-LINE ARGUMENTS: To get the search pattern and the filename from the user.
 * 2. FILE I/O: To open and read the target file.
 * 3. STRING MANIPULATION: To search for the pattern within each line of the file.
 * 4. ERROR HANDLING: To manage cases where the user provides wrong input or the
 *    file doesn't exist.
 *
 * THE PLAN:
 * 1. Get two arguments from the command line: the search `pattern` and the `filename`.
 * 2. Open the `filename` for reading.
 * 3. Read the file one line at a time.
 * 4. For each line, check if it contains the `pattern`.
 * 5. If it does, print that line to the console.
 * 6. Close the file and exit.
 *
 * Let's get started!
 */

// --- Required Headers ---
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // We need this for strstr()

// The main function signature for programs that accept command-line arguments.
int main(int argc, char *argv[])
{
    // --- Step 1: Validate Command-Line Arguments ---

    // `argc` is the count of arguments. We expect exactly 3:
    // argv[0]: The program name (e.g., ./27_build_your_own_grep)
    // argv[1]: The search pattern (e.g., "main")
    // argv[2]: The filename (e.g., "27_build_your_own_grep.c")
    if (argc != 3)
    {
        fprintf(stderr, "Usage: %s <pattern> <filename>\n", argv[0]);
        return 1; // Return an error code.
    }

    // Store the arguments in clearly named variables for readability.
    char *pattern = argv[1];
    char *filename = argv[2];

    // --- Step 2: Open the File ---

    // We declare a FILE POINTER. This pointer will hold the reference to our open file.
    FILE *file_pointer;

    // `fopen()` attempts to open the file.
    // The first argument is the path to the file.
    // The second argument, "r", specifies that we want to open it in READ mode.
    file_pointer = fopen(filename, "r");

    // If `fopen()` fails (e.g., the file doesn't exist), it returns NULL.
    // We must always check for this!
    if (file_pointer == NULL)
    {
        // `perror()` is a great function for printing file-related errors.
        // It prints your custom message, followed by a colon, and then the
        // system's human-readable error message for why the operation failed.
        perror("Error opening file");
        return 1;
    }

    // --- Step 3 & 4: Read File Line by Line and Search ---

    char line_buffer[2048]; // A buffer to hold one line of text from the file.

    printf("Searching for \"%s\" in file \"%s\":\n\n", pattern, filename);

    // This `while` loop is the standard, safe way to read a file line-by-line.
    // `fgets()` reads one line (or up to 2047 characters + null terminator)
    // from `file_pointer` and stores it in `line_buffer`.
    // It returns NULL when it reaches the end of the file, which ends the loop.
    //
    // LIMITATION: a line longer than 2047 characters arrives in several pieces,
    // one per loop. We would then print only the piece that matched, and miss a
    // match that straddles two pieces. Real `grep` handles lines of any length;
    // for ordinary text files this buffer is plenty.
    while (fgets(line_buffer, sizeof(line_buffer), file_pointer) != NULL)
    {
        // --- The Core Logic: Searching for a Substring ---

        // `strstr()` is the key function here. It searches for the first
        // occurrence of the `pattern` string within the `line_buffer` string.
        // - If it finds a match, it returns a POINTER to the beginning of the match.
        // - If no match is found, it returns NULL.
        if (strstr(line_buffer, pattern) != NULL)
        {
            // A match was found! Print the entire line.
            // We use `printf("%s", ...)` and not `printf("%s\n", ...)` because
            // `fgets()` already includes the newline character `\n` at the
            // end of the line it reads.
            printf("%s", line_buffer);
        }
    }

    // --- Step 5: Clean Up ---

    // It is crucial to close the file when you are done with it.
    // `fclose()` releases the file handle back to the operating system.
    fclose(file_pointer);

    return 0; // Success!
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Congratulations! You've just built your own version of `grep`. This project is a
 * major milestone. It demonstrates your ability to write a complete, useful
 * command-line tool that interacts with the file system, processes user input,
 * and performs core logic using string manipulation.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal and compile the program:
 *    `cc -Wall -Wextra -std=c17 -o 27_build_your_own_grep 27_build_your_own_grep.c`
 *
 * 2. Run it! A great first test is to make it search for something in its own source code.
 *    Let's search for every line containing the word "main":
 *    `./27_build_your_own_grep main 27_build_your_own_grep.c`
 *
 * 3. Try another one. Search for every line containing the `strstr` function:
 *    `./27_build_your_own_grep strstr 27_build_your_own_grep.c`
 *
 * 4. For a more realistic example, create a sample data file:
 *    `echo "Hello world, this is a test." > data.txt`
 *    `echo "Another line with some more data." >> data.txt`
 *    `echo "The world is full of interesting tests." >> data.txt`
 *    `echo "A final line without the keyword." >> data.txt`
 *
 *    Now search this new file for the word "world":
 *    `./27_build_your_own_grep world data.txt`
 *
 *    You should see the first and third lines printed to your console.
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 27_build_your_own_grep 27_build_your_own_grep.c
./27_build_your_own_grep main 27_build_your_own_grep.c

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Print the line number before each matching line, like grep -n.
  2. Add a -c option that prints only the number of matching lines.
  3. Read from standard input when no file name is given, so cat file | ./27_build_your_own_grep pattern works.

Hash Table Implementation

What you’ll learn: building a hash table with separate chaining: a hash function, insert, search, delete and cleanup.

Before you start: Lessons 13 and 20.

This lesson is a project: a data structure you build from scratch.

So far, we’ve seen arrays (fast access by index, slow search) and linked lists (slow search, flexible size). Now, we will build a data structure that offers the best of both worlds: the HASH TABLE (also known as a Hash Map).

What Is a Hash Table?

A Hash Table is a data structure that maps KEYS to VALUES. You give it a key (e.g., a person’s name), and it can very quickly find the associated value (e.g., their phone number). The goal is to achieve an average time complexity of O(1) – constant time – for insertion, deletion, and searching. This is incredibly fast and is why hash tables are used everywhere, from databases to compiler symbol tables to the dictionaries/maps in modern languages like Python and JavaScript.

How Does It Work?

  1. THE HASH FUNCTION: The magic is in the HASH FUNCTION. This is a function that takes a key (which can be a string, number, etc.) and converts it into an integer index. This index tells us where to store the value in an underlying array. A good hash function distributes keys evenly across the array to minimize collisions.

  2. THE ARRAY (TABLE): The hash table uses a simple array as its backbone. The index generated by the hash function corresponds to a “bucket” or “slot” in this array.

  3. COLLISION HANDLING: What if two different keys hash to the same index? This is called a COLLISION. It’s inevitable. We will handle collisions using a method called SEPARATE CHAINING. This means that each slot in our array won’t hold the value directly. Instead, each slot will be a pointer to the HEAD of a LINKED LIST. If a collision occurs, we just add the new key-value pair as a new node in that linked list.

Our Implementation Plan

  1. Define an Entry struct (a node in our linked list for a key-value pair).
  2. Define a HashTable struct (which holds the main array of entry pointers).
  3. Write a hash_function to convert string keys to array indices.
  4. Implement ht_create to initialize the table.
  5. Implement ht_insert to add or update key-value pairs.
  6. Implement ht_search to retrieve a value by its key.
  7. Implement ht_delete to remove a key-value pair.
  8. Implement ht_free to clean up all allocated memory.

The Hash Function

unsigned int hash_function(const char *key)
{
    unsigned long int value = 0;
    size_t key_len = strlen(key);

    for (size_t i = 0; i < key_len; ++i)
    {
        value = value * 37 + (unsigned char)key[i];
    }

    return (unsigned int)(value % TABLE_SIZE);
}

This is a simple POLYNOMIAL hash function. For each character in the key, it multiplies the running value by 37 and adds the character’s code. Then it uses the modulo operator to bring the result within the bounds of our table size.

Why not just add up the character codes? Because then “stop” and “pots” (the same letters in a different order) would always collide. Multiplying before each addition makes the position of every character count. The running value is unsigned, so when it grows past the largest unsigned long it simply wraps around, which is well-defined and harmless for hashing.

A good hash function is crucial for performance, but this is fine for learning.

Full Source

/**
 * @file 28_hash_table_implementation.c
 * @brief Part 4, Lesson 28: Hash Table Implementation
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file is a major project: we will implement a Hash Table, one of the
 * most important and powerful data structures in all of computer science.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * PROJECT: IMPLEMENT A HASH TABLE
 *
 * So far, we've seen arrays (fast access by index, slow search) and linked lists
 * (slow search, flexible size). Now, we will build a data structure that offers
 * the best of both worlds: the HASH TABLE (also known as a Hash Map).
 *
 * WHAT IS A HASH TABLE?
 * A Hash Table is a data structure that maps KEYS to VALUES. You give it a key
 * (e.g., a person's name), and it can very quickly find the associated value
 * (e.g., their phone number). The goal is to achieve an average time complexity
 * of O(1) -- constant time -- for insertion, deletion, and searching. This is
 * incredibly fast and is why hash tables are used everywhere, from databases to
 * compiler symbol tables to the dictionaries/maps in modern languages like
 * Python and JavaScript.
 *
 * HOW DOES IT WORK?
 * 1. THE HASH FUNCTION: The magic is in the HASH FUNCTION. This is a function
 *    that takes a key (which can be a string, number, etc.) and converts it
 *    into an integer index. This index tells us where to store the value in
 *    an underlying array. A good hash function distributes keys evenly across
 *    the array to minimize collisions.
 *
 * 2. THE ARRAY (TABLE): The hash table uses a simple array as its backbone. The
 *    index generated by the hash function corresponds to a "bucket" or "slot"
 *    in this array.
 *
 * 3. COLLISION HANDLING: What if two different keys hash to the same index?
 *    This is called a COLLISION. It's inevitable. We will handle collisions
 *    using a method called SEPARATE CHAINING. This means that each slot in our
 *    array won't hold the value directly. Instead, each slot will be a pointer
 *    to the HEAD of a LINKED LIST. If a collision occurs, we just add the new
 *    key-value pair as a new node in that linked list.
 *
 * OUR IMPLEMENTATION PLAN:
 * 1. Define an `Entry` struct (a node in our linked list for a key-value pair).
 * 2. Define a `HashTable` struct (which holds the main array of entry pointers).
 * 3. Write a `hash_function` to convert string keys to array indices.
 * 4. Implement `ht_create` to initialize the table.
 * 5. Implement `ht_insert` to add or update key-value pairs.
 * 6. Implement `ht_search` to retrieve a value by its key.
 * 7. Implement `ht_delete` to remove a key-value pair.
 * 8. Implement `ht_free` to clean up all allocated memory.
 */

// --- Required Headers ---
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// --- Part 1: Data Structures and Constants ---

#define TABLE_SIZE 10 // A small size for easy demonstration

// A single key-value entry. This is also a node in a linked list.
typedef struct Entry
{
    char *key;
    char *value;
    struct Entry *next;
} Entry;

// The Hash Table itself.
typedef struct HashTable
{
    // The table is an array of pointers to Entry structs.
    // This is an array of linked list heads.
    Entry **entries;
} HashTable;

// --- Function Prototypes (Lesson 7) ---
// Declaring the functions up front gives a summary of the file. Their
// definitions, with the explanations, follow below.
unsigned int hash_function(const char *key);
HashTable *ht_create(void);
char *copy_string(const char *text);
Entry *create_entry(const char *key, const char *value);
void ht_insert(HashTable *hashtable, const char *key, const char *value);
char *ht_search(HashTable *hashtable, const char *key);
void ht_delete(HashTable *hashtable, const char *key);
void ht_free(HashTable *hashtable);
void ht_print(HashTable *hashtable);

// --- Part 2: The Hash Function ---

/*
 * This is a simple POLYNOMIAL hash function. For each character in the key,
 * it multiplies the running value by 37 and adds the character's code. Then
 * it uses the modulo operator to bring the result within the bounds of our
 * table size.
 *
 * Why not just add up the character codes? Because then "stop" and "pots"
 * (the same letters in a different order) would always collide. Multiplying
 * before each addition makes the position of every character count.
 *
 * `value` is unsigned, so if it grows past the largest `unsigned long` it
 * simply wraps around to small numbers again. That is well-defined for
 * unsigned types and harmless for hashing. (Overflow of a SIGNED integer, by
 * contrast, is undefined behavior.)
 *
 * A good hash function is crucial for performance, but this is fine for learning.
 */
unsigned int hash_function(const char *key)
{
    unsigned long int value = 0;
    size_t key_len = strlen(key);

    for (size_t i = 0; i < key_len; ++i)
    {
        // The cast makes the character code 0-255 even where `char` is
        // signed and the key holds non-ASCII bytes.
        value = value * 37 + (unsigned char)key[i];
    }

    // Return the value modulo the table size. The result is always less
    // than TABLE_SIZE, so converting it to `unsigned int` loses nothing; the
    // cast says so.
    return (unsigned int)(value % TABLE_SIZE);
}

// --- Part 3: Core Hash Table Operations ---

/**
 * @brief Creates and initializes a new hash table.
 * @return A pointer to the newly created HashTable, or NULL on failure.
 */
HashTable *ht_create(void)
{
    // Allocate memory for the HashTable structure itself.
    HashTable *hashtable = malloc(sizeof(HashTable));
    if (hashtable == NULL)
    {
        return NULL;
    }

    // Allocate memory for the array of Entry pointers ("buckets").
    // We use calloc to initialize all pointers in the array to NULL.
    hashtable->entries = calloc(TABLE_SIZE, sizeof(Entry *));
    if (hashtable->entries == NULL)
    {
        free(hashtable); // Clean up partially allocated memory
        return NULL;
    }

    return hashtable;
}

/**
 * @brief Makes a copy of a string on the heap.
 *
 * `strcpy` never checks the size of its destination, so it is only safe when
 * we know the destination is big enough. Here we are sure: we allocate
 * exactly `strlen(text) + 1` bytes, room for every character plus the `\0`.
 *
 * Like `create_node` in Lesson 20, we stop the program if `malloc` fails.
 * Every caller can then rely on getting a valid copy back.
 */
char *copy_string(const char *text)
{
    char *copy = malloc(strlen(text) + 1);
    if (copy == NULL)
    {
        fprintf(stderr, "Error: Memory allocation failed!\n");
        exit(1);
    }
    strcpy(copy, text);
    return copy;
}

/**
 * @brief Creates a new key-value entry.
 */
Entry *create_entry(const char *key, const char *value)
{
    Entry *entry = malloc(sizeof(Entry));
    if (entry == NULL)
    {
        fprintf(stderr, "Error: Memory allocation failed!\n");
        exit(1);
    }

    entry->key = copy_string(key);
    entry->value = copy_string(value);
    entry->next = NULL;

    return entry;
}

/**
 * @brief Inserts a key-value pair into the hash table. Updates value if key exists.
 */
void ht_insert(HashTable *hashtable, const char *key, const char *value)
{
    unsigned int index = hash_function(key);
    Entry *current_entry = hashtable->entries[index];

    // Traverse the linked list at this index to see if the key already exists.
    while (current_entry != NULL)
    {
        if (strcmp(current_entry->key, key) == 0)
        {
            // Key found, so update the value. Copy the new value BEFORE
            // freeing the old one: `value` may point at the old value itself
            // (as in `ht_insert(table, "name", ht_search(table, "name"))`),
            // and after `free` that memory must not be read.
            char *new_value = copy_string(value);
            free(current_entry->value);
            current_entry->value = new_value;
            return; // We're done.
        }
        current_entry = current_entry->next;
    }

    // Key not found. Create a new entry and insert it at the head of the list.
    Entry *new_entry = create_entry(key, value);
    new_entry->next = hashtable->entries[index];
    hashtable->entries[index] = new_entry;
}

/**
 * @brief Searches for a key in the hash table.
 * @return The value associated with the key, or NULL if the key is not found.
 */
char *ht_search(HashTable *hashtable, const char *key)
{
    unsigned int index = hash_function(key);
    Entry *entry = hashtable->entries[index];

    // Traverse the linked list at the calculated index.
    while (entry != NULL)
    {
        if (strcmp(entry->key, key) == 0)
        {
            // Key found! Return its value.
            return entry->value;
        }
        entry = entry->next;
    }

    // Key not found.
    return NULL;
}

/**
 * @brief Deletes a key-value pair from the hash table.
 */
void ht_delete(HashTable *hashtable, const char *key)
{
    unsigned int index = hash_function(key);
    Entry *entry = hashtable->entries[index];
    Entry *prev = NULL;

    // Traverse the list to find the entry to delete
    while (entry != NULL && strcmp(entry->key, key) != 0)
    {
        prev = entry;
        entry = entry->next;
    }

    // If entry is NULL, the key wasn't found.
    if (entry == NULL)
    {
        return;
    }

    // Relink the list
    if (prev == NULL)
    {
        // The item to delete is the head of the list
        hashtable->entries[index] = entry->next;
    }
    else
    {
        // The item is in the middle or at the end
        prev->next = entry->next;
    }

    // Free the memory for the deleted entry
    free(entry->key);
    free(entry->value);
    free(entry);
}

/**
 * @brief Frees all memory used by the hash table.
 */
void ht_free(HashTable *hashtable)
{
    for (int i = 0; i < TABLE_SIZE; ++i)
    {
        Entry *entry = hashtable->entries[i];
        while (entry != NULL)
        {
            Entry *temp = entry;
            entry = entry->next;
            free(temp->key);
            free(temp->value);
            free(temp);
        }
    }

    free(hashtable->entries);
    free(hashtable);
}

/**
 * @brief A helper function to print the contents of the hash table.
 */
void ht_print(HashTable *hashtable)
{
    printf("\n--- Hash Table Contents ---\n");
    for (int i = 0; i < TABLE_SIZE; ++i)
    {
        printf("Bucket[%d]: ", i);
        Entry *entry = hashtable->entries[i];
        if (entry == NULL)
        {
            printf("~empty~\n");
            continue;
        }
        while (entry != NULL)
        {
            printf(" -> [\"%s\": \"%s\"]", entry->key, entry->value);
            entry = entry->next;
        }
        printf("\n");
    }
    printf("---------------------------\n");
}

// --- Main Function for Demonstration ---
int main(void)
{
    printf("Creating a new hash table.\n");
    HashTable *ht = ht_create();
    if (ht == NULL)
    {
        fprintf(stderr, "Error: Could not create the hash table.\n");
        return 1;
    }

    printf("\nInserting key-value pairs...\n");
    ht_insert(ht, "name", "John Doe");
    ht_insert(ht, "age", "30");
    // With TABLE_SIZE 10, "age" and "city" hash to the same bucket (5): a
    // COLLISION. The table output below shows them chained in one list.
    ht_insert(ht, "city", "New York");
    ht_insert(ht, "country", "USA");
    ht_insert(ht, "language", "C");

    ht_print(ht);

    printf("\nSearching for keys...\n");
    char *name = ht_search(ht, "name");
    char *job = ht_search(ht, "job"); // This key doesn't exist

    printf("Value for 'name': %s\n", name ? name : "Not Found");
    printf("Value for 'job': %s\n", job ? job : "Not Found");

    printf("\nDeleting key 'age'...\n");
    ht_delete(ht, "age");
    ht_print(ht);

    printf("\nUpdating key 'city'...\n");
    ht_insert(ht, "city", "Los Angeles"); // This should update the existing entry
    ht_print(ht);

    printf("\nFreeing all hash table memory...\n");
    ht_free(ht);
    printf("Memory freed successfully.\n");

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Congratulations on building a complete hash table! You've implemented one of the
 * most fundamental and high-performance data structures. You used dynamic memory,
 * pointers to pointers, structs, linked lists (for collision handling), and
 * string manipulation. This is a massive achievement.
 *
 * You now understand the core principles behind the dictionaries, maps, and objects
 * that power modern, high-level programming languages.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal and compile the program:
 *    `cc -Wall -Wextra -std=c17 -o 28_hash_table_implementation 28_hash_table_implementation.c`
 *
 * 2. Run the executable:
 *    `./28_hash_table_implementation`
 *
 * 3. Observe the output. Pay close attention to how the `ht_print` function shows
 *    the state of the table after each operation, especially how collisions
 *    result in linked lists within a single bucket.
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 28_hash_table_implementation 28_hash_table_implementation.c
./28_hash_table_implementation

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Add int ht_count(const HashTable *table) that counts the stored entries.
  2. Change TABLE_SIZE to 1 and run the lesson. It still works: why, and what happens to the speed?
  3. Add a function that prints how many entries each bucket holds, to see how evenly the keys spread.

Tiny Shell

What you’ll learn: how a shell runs programs: reading a command, splitting it into arguments, fork, execvp and waitpid.

Before you start: Lessons 15 and 26.

This lesson is a project: a working command-line shell.

A SHELL is a command-line interpreter. It’s the program that gives you a prompt (like $ or > ), reads your input (like ls -l), and tells the operating system to execute that command. In this lesson, we will build one.

This project is the culmination of many systems programming concepts. It’s how a computer can run a program from within another program. The core of any shell revolves around a simple, powerful loop:

  1. READ: Read a command from the user.
  2. PARSE: Break the command into a program name and its arguments.
  3. FORK: Create a new PROCESS (a copy of the shell).
  4. EXEC: The new process REPLACES itself with the command to be run.
  5. WAIT: The original shell process waits for the command to finish.

Our PARSE step only splits the line at spaces. A real shell does much more, quoting for one: in bash, echo "Hello from my own shell!" prints the words without the quote marks, while TinyShell passes the quote marks on to echo as part of its arguments, and they are printed.

The Key System Calls

To accomplish this, we will use three of the most important functions in Unix/Linux programming:

  • fork(): This creates a new child process, which is an exact duplicate of the parent process (our shell). It’s like cloning our program. The parent gets the child’s process ID, and the child gets 0.

  • execvp(): (The “exec” family of functions). This function REPLACES the current process’s memory space with a new program. When the child process calls execvp, it ceases to be a copy of our shell and BECOMES the ls program (or whatever was requested). execvp is special because it searches the system’s PATH for the executable, just like a real shell.

  • waitpid(): This tells the parent process (our shell) to pause and wait until a specific child process has finished executing. This ensures our shell prompt doesn’t reappear until the command’s output is complete.

If execvp fails (for example, the command does not exist), it returns, and the child is still a copy of our shell. It must stop at once with _exit() rather than exit(): exit() would also clean up the stdio buffers the child copied from its parent, and when the shell reads its commands from a file that cleanup can rewind the input the two processes share, making the parent read the same commands over and over.

Let’s build our own bash!

Full Source

/**
 * @file 29_tiny_shell.c
 * @brief Part 4, Lesson 29: Build Your Own Tiny Shell
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file implements a basic command-line shell, a program that reads
 * commands from the user and executes them. This is a capstone project for
 * understanding process management in a Unix-like environment.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * PROJECT: BUILD A TINY SHELL
 *
 * A SHELL is a command-line interpreter. It's the program that gives you a
 * prompt (like `$` or `> `), reads your input (like `ls -l`), and tells the
 * operating system to execute that command. In this lesson, we will build one.
 *
 * This project is the culmination of many systems programming concepts. It's how
 * a computer can run a program from within another program. The core of any
 * shell revolves around a simple, powerful loop:
 *
 * 1. READ: Read a command from the user.
 * 2. PARSE: Break the command into a program name and its arguments.
 * 3. FORK: Create a new PROCESS (a copy of the shell).
 * 4. EXEC: The new process REPLACES itself with the command to be run.
 * 5. WAIT: The original shell process waits for the command to finish.
 *
 * THE KEY SYSTEM CALLS
 * To accomplish this, we will use three of the most important functions in
 * Unix/Linux programming:
 *
 * - fork(): This creates a new child process, which is an exact duplicate of
 *   the parent process (our shell). It's like cloning our program. The parent
 *   gets the child's process ID, and the child gets 0.
 *
 * - execvp(): (The "exec" family of functions). This function REPLACES the
 *   current process's memory space with a new program. When the child process
 *   calls `execvp`, it ceases to be a copy of our shell and BECOMES the `ls`
 *   program (or whatever was requested). `execvp` is special because it
 *   searches the system's PATH for the executable, just like a real shell.
 *
 * - waitpid(): This tells the parent process (our shell) to pause and wait
 *   until a specific child process has finished executing. This ensures our
 *   shell prompt doesn't reappear until the command's output is complete.
 *
 * Let's build our own `bash`!
 */

// --- Required Headers ---
#include <stdio.h>
#include <stdlib.h>
#include <string.h>   // For strtok()
#include <unistd.h>   // For fork(), execvp(), _exit()
#include <sys/wait.h> // For waitpid()

// --- Constants ---
#define MAX_LINE 80 // The maximum length of a command
#define MAX_ARGS 20 // The maximum number of arguments

// --- Function Prototypes (Lesson 7) ---
void parse_input(char *line, char **args);
void discard_remaining_input(void);

// --- Function to Parse Input ---
// This function takes a raw command line string and breaks it into tokens.
// It populates the `args` array and is a crucial pre-processing step.
void parse_input(char *line, char **args)
{
    int i = 0;
    // `strtok` splits a string by a delimiter. We use space, tab, and newline.
    // The first call to `strtok` uses the line; subsequent calls use NULL
    // to continue tokenizing the same string.
    char *token = strtok(line, " \t\n");

    while (token != NULL && i < MAX_ARGS - 1)
    {
        args[i] = token;
        i++;
        token = strtok(NULL, " \t\n");
    }
    // The `execvp` function requires the argument array to be terminated by a NULL pointer.
    args[i] = NULL;
}

void discard_remaining_input(void)
{
    int ch;

    while ((ch = getchar()) != '\n' && ch != EOF)
    {
        // Consume the rest of an overlong command so it is not treated as a new one.
    }
}

int main(void)
{
    char *args[MAX_ARGS]; // Array to hold parsed command arguments
    char line[MAX_LINE];  // Buffer to hold the raw input line
    int should_run = 1;   // Flag to control the main loop

    printf("Welcome to TinyShell! Type 'exit' to quit.\n");

    while (should_run)
    {
        printf("> ");
        // We must flush stdout to ensure the prompt `>` appears before `fgets` waits for input.
        fflush(stdout);

        // --- Step 1: Read Input ---
        if (fgets(line, sizeof(line), stdin) == NULL)
        {
            // If fgets returns NULL, it's an end-of-file (Ctrl+D) or an error.
            printf("\nExiting TinyShell.\n");
            break;
        }

        if (strchr(line, '\n') == NULL && !feof(stdin))
        {
            discard_remaining_input();
            printf("Command too long. Maximum length is %d characters.\n", MAX_LINE - 2);
            continue;
        }

        // --- Step 2: Parse Input ---
        parse_input(line, args);

        // If the user just hits Enter, args[0] will be NULL. Loop again.
        if (args[0] == NULL)
        {
            continue;
        }

        // --- Handle Built-in Commands ---
        // We handle `exit` ourselves; it's not an external program.
        if (strcmp(args[0], "exit") == 0)
        {
            should_run = 0;
            continue;
        }

        // --- Step 3: Fork a Child Process ---
        pid_t pid = fork();

        if (pid < 0)
        {
            // Forking failed. This is a serious error.
            perror("fork failed");
            exit(1);
        }
        else if (pid == 0)
        {
            // --- This is the CHILD PROCESS ---
            // --- Step 4: Execute the Command ---

            // `execvp` takes the program name (args[0]) and the full argument vector.
            // If it is successful, it NEVER returns. The child process becomes `ls` (or whatever).
            if (execvp(args[0], args) == -1)
            {
                // If `execvp` returns, an error occurred (e.g., command not found).
                perror("execvp failed");

                // IMPORTANT: The child must end here, or it would carry on
                // running a second copy of the shell's loop. We use `_exit()`,
                // not `exit()`. The child shares the parent's open files, and
                // `exit()` would also clean up the stdio buffers it copied from
                // the parent. When the shell's input is a file
                // (`./29_tiny_shell < commands.txt`), that cleanup can move the
                // shared read position back, so the parent reads the same lines
                // again, forever. `_exit()` (from <unistd.h>) ends the process
                // at once, without touching stdio. 127 is the exit status shells
                // use for "command not found".
                _exit(127);
            }
        }
        else
        {
            // --- This is the PARENT PROCESS ---
            // --- Step 5: Wait for the Child to Complete ---
            int status;
            // `waitpid` waits for the process with the given `pid` to finish.
            // The `&status` argument can be used to get info on how the child exited.
            waitpid(pid, &status, 0);
        }
    }

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * You have successfully built a functional command-line shell! It can run almost
 * any standard command-line program on your system. You have directly manipulated
 * processes, the fundamental unit of execution in an operating system.
 *
 * This Read-Parse-Fork-Exec-Wait loop is the foundation of not just shells, but
 * also IDE "Run" buttons, web servers that spawn worker processes, and many other
 * powerful system tools.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal and compile the program:
 *    `cc -Wall -Wextra -std=c17 -o 29_tiny_shell 29_tiny_shell.c`
 *
 * 2. Run your new shell:
 *    `./29_tiny_shell`
 *
 * 3. You will see a `>` prompt. Try running some commands!
 *    > ls
 *    > ls -l
 *    > pwd
 *    > echo "Hello from my own shell!"
 *    > whoami
 *
 *    The `echo` line prints the quote marks too. In bash, quotes group words
 *    and are then removed, so `echo` gets one argument. Our parser only splits
 *    on spaces, so `echo` gets five: `"Hello`, `from`, `my`, `own` and
 *    `shell!"`, quote marks included. Handling quotes is one of the many jobs
 *    a real shell does for you.
 *
 * 4. When you are finished, type `exit` to quit your shell and return to the
 *    regular system shell.
 *    > exit
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 29_tiny_shell 29_tiny_shell.c
./29_tiny_shell

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Add a built-in pwd command using getcwd.
  2. Print the exit status of each command after it finishes, using WIFEXITED and WEXITSTATUS.
  3. Add a built-in cd command with chdir. Why can cd not be run as a child process?

Multithreaded File Analyzer

What you’ll learn: running work in parallel with POSIX threads, race conditions, and protecting shared data with a mutex.

Before you start: Lessons 13, 14 and 29.

This lesson is a project: putting every core of your CPU to work.

So far, all our programs have run in a single sequence of execution. They do one thing at a time. This is called single-threaded execution. But modern CPUs have multiple cores, each capable of running instructions independently. How can we take advantage of this power? The answer is MULTITHREADING.

Process vs. Thread

  • A PROCESS is a running instance of a program (like our tiny_shell). It has its own dedicated memory space, file descriptors, etc. fork() creates a new process.
  • A THREAD is a “lightweight” path of execution within a single process. Multiple threads within the same process SHARE the same memory space. This makes communication between them easy (they can just access the same variables), but it also introduces a huge challenge: managing that shared access safely.

The Challenge: Race Conditions

Imagine two threads trying to increment the same global counter (global_count++). This operation is not ATOMIC (it’s not one single instruction). It’s really:

  1. Read the value of global_count from memory into a CPU register.
  2. Increment the value in the register.
  3. Write the new value back to memory.

A RACE CONDITION occurs if Thread 1 reads the value (say, 5), but before it can write back 6, Thread 2 also reads the value (still 5). Both threads will compute 6 and write it back. The counter should be 7, but it’s only 6! We lost an update.

The Solution: Mutexes

A MUTEX (MUTual EXclusion) is a lock. It’s a programming primitive that ensures only one thread can access a “critical section” of code at a time. The workflow is:

  1. Thread A acquires the lock. No other thread can acquire it until A is done.
  2. Thread A safely modifies the shared data.
  3. Thread A releases the lock.
  4. Thread B, which was waiting, can now acquire the lock and do its work.

Our Plan

We will write a program that counts the characters, words, and lines in a large file. To speed it up, we will:

  1. Read the entire file into one large memory buffer.
  2. Divide the buffer into chunks, one for each thread.
  3. Launch multiple threads, each running a worker function to analyze its chunk.
  4. Each thread will calculate its local counts.
  5. After finishing, each thread will lock a global mutex, add its local counts to a global total, and then unlock the mutex.
  6. The main thread will wait for all worker threads to complete and then print the result.

We will use the POSIX Threads (pthreads) library, the standard threading API on Unix-like systems such as Linux and macOS.

Like most pthread functions, pthread_create returns 0 on success and an error number on failure. The program checks it and only waits for (joins) the threads that really started.

Full Source

/**
 * @file 30_multithreaded_file_analyzer.c
 * @brief Part 4, Lesson 30: Multithreaded File Analyzer
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file is a project that harnesses the power of multiple CPU cores
 * by using threads to analyze a large file in parallel.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * PROJECT: HARNESS MULTI-CORE POWER WITH THREADS
 *
 * So far, all our programs have run in a single sequence of execution. They do
 * one thing at a time. This is called single-threaded execution. But modern
 * CPUs have multiple cores, each capable of running instructions independently.
 * How can we take advantage of this power? The answer is MULTITHREADING.
 *
 * PROCESS vs. THREAD
 * - A PROCESS is a running instance of a program (like our `tiny_shell`). It has
 *   its own dedicated memory space, file descriptors, etc. `fork()` creates a new process.
 * - A THREAD is a "lightweight" path of execution *within* a single process.
 *   Multiple threads within the same process SHARE the same memory space. This
 *   makes communication between them easy (they can just access the same variables),
 *   but it also introduces a huge challenge: managing that shared access safely.
 *
 * THE CHALLENGE: RACE CONDITIONS
 * Imagine two threads trying to increment the same global counter (`global_count++`).
 * This operation is not ATOMIC (it's not one single instruction). It's really:
 * 1. Read the value of `global_count` from memory into a CPU register.
 * 2. Increment the value in the register.
 * 3. Write the new value back to memory.
 *
 * A RACE CONDITION occurs if Thread 1 reads the value (say, 5), but before it
 * can write back 6, Thread 2 also reads the value (still 5). Both threads will
 * compute 6 and write it back. The counter should be 7, but it's only 6! We lost an update.
 *
 * THE SOLUTION: MUTEXES
 * A MUTEX (MUTual EXclusion) is a lock. It's a programming primitive that ensures
 * only one thread can access a "critical section" of code at a time. The workflow is:
 * 1. Thread A acquires the lock. No other thread can acquire it until A is done.
 * 2. Thread A safely modifies the shared data.
 * 3. Thread A releases the lock.
 * 4. Thread B, which was waiting, can now acquire the lock and do its work.
 *
 * OUR PLAN:
 * We will write a program that counts the characters, words, and lines in a large
 * file. To speed it up, we will:
 * 1. Read the entire file into one large memory buffer.
 * 2. Divide the buffer into chunks, one for each thread.
 * 3. Launch multiple threads, each running a worker function to analyze its chunk.
 * 4. Each thread will calculate its *local* counts.
 * 5. After finishing, each thread will lock a global mutex, add its local counts
 *    to a global total, and then unlock the mutex.
 * 6. The main thread will wait for all worker threads to complete and then print the result.
 *
 * We will use the POSIX Threads (pthreads) library, the standard threading API
 * on Unix-like systems such as Linux and macOS.
 */

// --- Required Headers ---
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h> // The main header for POSIX Threads
#include <ctype.h>   // For isspace()

// --- Constants and Global Data ---
#define NUM_THREADS 4

// This struct will hold the final, combined results. This is our SHARED DATA.
typedef struct
{
    long long total_chars;
    long long total_words;
    long long total_lines;
} GlobalCounts;

GlobalCounts g_counts = {0, 0, 0}; // Initialize global counts
pthread_mutex_t g_mutex;           // The global MUTEX to protect g_counts

// This struct holds the information we need to pass to each thread.
typedef struct
{
    char *data_chunk;       // Pointer to the start of this thread's data
    long chunk_size;        // How many bytes this thread should process
    int starts_inside_word; // True when this chunk begins in the middle of a word
} ThreadData;

// --- Function Prototypes (Lesson 7) ---
void *analyze_chunk(void *arg);

// --- The Worker Function ---
// This is the function that each thread will execute.
void *analyze_chunk(void *arg)
{
    ThreadData *data = (ThreadData *)arg;

    // --- Step 1: Perform analysis on local variables ---
    // We do NOT want to lock the mutex for every character we count.
    // That would be extremely slow and defeat the purpose of threading.
    // Instead, each thread calculates its own sub-total.
    long long local_chars = 0;
    long long local_words = 0;
    long long local_lines = 0;
    int in_word = data->starts_inside_word; // Continue an in-progress word across chunks

    for (long i = 0; i < data->chunk_size; i++)
    {
        char c = data->data_chunk[i];
        local_chars++;

        if (c == '\n')
        {
            local_lines++;
        }

        if (isspace((unsigned char)c))
        {
            in_word = 0;
        }
        else if (in_word == 0)
        {
            in_word = 1;
            local_words++;
        }
    }

    // --- Step 2: Lock the mutex and update the global state ---
    // This is the CRITICAL SECTION. Only one thread can be in here at a time.
    pthread_mutex_lock(&g_mutex);

    g_counts.total_chars += local_chars;
    g_counts.total_words += local_words;
    g_counts.total_lines += local_lines;

    pthread_mutex_unlock(&g_mutex); // Release the lock!

    return NULL;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        return 1;
    }

    // --- Read entire file into memory ---
    FILE *file = fopen(argv[1], "rb");
    if (!file)
    {
        perror("Error opening file");
        return 1;
    }

    if (fseek(file, 0, SEEK_END) != 0)
    {
        perror("Error seeking to end of file");
        fclose(file);
        return 1;
    }

    long file_size = ftell(file);
    if (file_size < 0)
    {
        perror("Error determining file size");
        fclose(file);
        return 1;
    }

    if (fseek(file, 0, SEEK_SET) != 0)
    {
        perror("Error rewinding file");
        fclose(file);
        return 1;
    }

    char *file_buffer = NULL;
    if (file_size > 0)
    {
        file_buffer = malloc((size_t)file_size);
    }

    if (file_size > 0 && !file_buffer)
    {
        fprintf(stderr, "Could not allocate memory for file\n");
        fclose(file);
        return 1;
    }

    if (file_size > 0 && fread(file_buffer, 1, (size_t)file_size, file) != (size_t)file_size)
    {
        fprintf(stderr, "Error reading file\n");
        free(file_buffer);
        fclose(file);
        return 1;
    }
    fclose(file);
    printf("Successfully read %ld bytes from %s.\n", file_size, argv[1]);

    if (file_size == 0)
    {
        printf("File is empty. Nothing to analyze.\n");
        printf("\n--- Analysis Complete ---\n");
        printf("Total Characters: %lld\n", g_counts.total_chars);
        printf("Total Words:      %lld\n", g_counts.total_words);
        printf("Total Lines:      %lld\n", g_counts.total_lines);
        printf("-------------------------\n");
        return 0;
    }

    // --- Initialize Threads and Mutex ---
    pthread_t threads[NUM_THREADS];
    ThreadData thread_args[NUM_THREADS];
    int threads_started = 0;

    // Like most pthread functions, these return 0 on success and an error
    // number on failure (they do not use -1 and errno).
    if (pthread_mutex_init(&g_mutex, NULL) != 0) // Initialize the mutex
    {
        fprintf(stderr, "Could not initialize the mutex\n");
        free(file_buffer);
        return 1;
    }

    long chunk_size = file_size / NUM_THREADS;
    for (int i = 0; i < NUM_THREADS; i++)
    {
        long chunk_start = i * chunk_size;

        thread_args[i].data_chunk = file_buffer + chunk_start;
        thread_args[i].chunk_size = (i == NUM_THREADS - 1) ? (file_size - chunk_start) : chunk_size;
        thread_args[i].starts_inside_word =
            (chunk_start > 0 && !isspace((unsigned char)file_buffer[chunk_start - 1]));

        printf("Launching thread %d to process %ld bytes.\n", i, thread_args[i].chunk_size);
        // `pthread_create` starts a new thread executing `analyze_chunk`
        // and passes it a pointer to its `thread_args`. It can fail, for
        // example when the system is out of resources. Then `threads[i]` is not
        // a real thread, so we must not wait for it.
        if (pthread_create(&threads[i], NULL, analyze_chunk, &thread_args[i]) != 0)
        {
            fprintf(stderr, "Could not start thread %d\n", i);
            break;
        }
        threads_started++;
    }

    // --- Wait for all threads to complete ---
    // Only join the threads that really started.
    for (int i = 0; i < threads_started; i++)
    {
        // `pthread_join` blocks the main thread until the specified thread finishes.
        pthread_join(threads[i], NULL);
        printf("Thread %d finished.\n", i);
    }

    // --- Clean up and Print Results ---
    pthread_mutex_destroy(&g_mutex); // Always destroy the mutex
    free(file_buffer);

    if (threads_started < NUM_THREADS)
    {
        // Part of the file was never analyzed, so the totals would be wrong.
        fprintf(stderr, "Analysis incomplete: only %d of %d threads ran.\n", threads_started, NUM_THREADS);
        return 1;
    }

    printf("\n--- Analysis Complete ---\n");
    printf("Total Characters: %lld\n", g_counts.total_chars);
    printf("Total Words:      %lld\n", g_counts.total_words);
    printf("Total Lines:      %lld\n", g_counts.total_lines);
    printf("-------------------------\n");

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * You've just written a parallel program! This is a huge step into high-performance
 * computing. You used POSIX threads to split a task, managed shared data with a
 * mutex to prevent race conditions, and successfully reaped the results.
 *
 * This pattern (split data, process in parallel, safely combine results) is a
 * cornerstone of concurrent programming.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * Compiling threaded programs requires linking the pthread library. You must add
 * the `-pthread` flag to your compile command.
 *
 * 1. Compile the program:
 *    `cc -Wall -Wextra -std=c17 -pthread -o 30_multithreaded_file_analyzer 30_multithreaded_file_analyzer.c`
 *
 * 2. To see the benefit, you need a large file. You can create one with this command
 *    (this creates a ~100MB file of random bytes. Its word and line counts are
 *    meaningless, since it is not text, but it is good for timing the analyzer):
 *    `dd if=/dev/urandom of=large_test_file.txt bs=1M count=100`
 *    (On Windows, run these commands in WSL, as this lesson needs POSIX threads.)
 *
 * 3. Run the analyzer on the large file:
 *    `./30_multithreaded_file_analyzer large_test_file.txt`
 *
 * 4. You can also run it on its own source code for a more readable result:
 *    `./30_multithreaded_file_analyzer 30_multithreaded_file_analyzer.c`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -pthread -o 30_multithreaded_file_analyzer 30_multithreaded_file_analyzer.c
./30_multithreaded_file_analyzer 30_multithreaded_file_analyzer.c

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Change the number of threads and time the program on a large file with time.
  2. Remove the mutex lock and unlock calls, build with -fsanitize=thread, and read the race report. Then put them back.
  3. Make each thread also count how many times the letter e appears.

Makefiles for Multi-File Projects

What you’ll learn: splitting a program into several files, header files and include guards, and building it with a Makefile.

Before you start: Lessons 7, 22 and 24.

Welcome to a pivotal moment in your C journey. Until now, we have worked with single source files. While great for learning, real-world applications are almost always split into multiple files for organization, reusability, and clarity.

Typing out long cc commands for every file becomes tedious and error-prone. Imagine a project with 50 files. This is where the make utility comes in.

What is a Makefile?

A make program reads a special file, by default named Makefile, to understand how to build your project. A Makefile contains a set of rules. Each rule has three parts: a target, its dependencies, and a recipe.

target: dependencies
    <tab>recipe (the command to run)
  • Target: The file we want to build (e.g., an executable or an object file).
  • Dependencies: The files the target needs in order to be built.
  • Recipe: The command(s) to execute to create the target.

Important: The recipe lines must start with a TAB character, not spaces.

The Project Structure

This lesson is intentionally split across multiple files to demonstrate how different C files work together:

  1. main.c – The entry point of the program. Contains the main function.
  2. helper.h – The header file that declares the helper functions.
  3. helper.c – The source file that defines the helper functions.
  4. Makefile – The instruction manual for the compiler.

helper.h

/**
 * @file helper.h
 * @brief Part 5, Lesson 31: Header File for the Helper Module
 * @author dunamismax
 * @date 06-15-2025
 *
 * This is a HEADER FILE. Its purpose is to declare the functions and types
 * that another part of the program (in this case, `helper.c`) provides.
 * It acts as a public "interface" or "contract".
 */

/*
 * =====================================================================================
 * |                            - LESSON: HEADER FILES -                               |
 * =====================================================================================
 *
 * WHAT IS A HEADER FILE?
 * In a multi-file project, we need a way for one `.c` file to know about the
 * functions available in another `.c` file. A HEADER FILE (with a `.h` extension)
 * serves this purpose. It contains the DECLARATIONS of functions, but not their
 * actual code (the DEFINITIONS).
 *
 * Any `.c` file that wants to use these functions can simply `#include` this
 * header file.
 *
 * --- The Include Guard ---
 *
 * What happens if a header file gets included more than once in the same
 * compilation process? Declaring a function twice is harmless, but headers
 * often also DEFINE things, such as a `struct` type, and defining those twice
 * is an error ("redefinition of 'struct ...'").
 * To prevent this, we use an INCLUDE GUARD. It's a standard preprocessor trick.
 *
 * `#ifndef HELPER_H`   // "If HELPER_H is NOT defined..."
 * `#define HELPER_H`   // "...then define it..."
 *
 *  // ... all the content of the header file goes here ...
 *
 * `#endif`             // "...and this is the end of the 'if' block."
 *
 * The first time the compiler sees this file, `HELPER_H` is not defined, so it
 * processes everything inside. It also defines `HELPER_H`. The second time it
 * sees this file, `HELPER_H` *is* defined, so the preprocessor skips everything
 * between `#ifndef` and `#endif`.
 *
 * The name `HELPER_H` should be unique to the file. A common convention is to
 * use the filename in all caps, replacing the `.` with an `_`.
 */

#ifndef HELPER_H
#define HELPER_H

// --- Function Prototypes ---

// This is a FUNCTION PROTOTYPE or FUNCTION DECLARATION.
// It tells the compiler everything it needs to know to *call* the function:
// its return type, its name, and the types of its parameters.
// The actual code for this function is in `helper.c`.
void say_hello_from_helper(void);

#endif // HELPER_H

helper.c

/**
 * @file helper.c
 * @brief Part 5, Lesson 31: Implementation File for the Helper Module
 * @author dunamismax
 * @date 06-15-2025
 *
 * This is a SOURCE FILE that provides the implementation for the
 * functions declared in `helper.h`.
 */

/*
 * =====================================================================================
 * |                          - LESSON: SOURCE FILES -                                 |
 * =====================================================================================
 *
 * WHAT IS A SOURCE IMPLEMENTATION FILE?
 * This `.c` file contains the actual code, the DEFINITIONS, for the functions
 * that were promised (declared) in the corresponding header file (`helper.h`).
 *
 * By separating the declaration (`.h`) from the definition (`.c`), we create
 * modular, reusable code. Another programmer could use our `helper` module by
 * just reading `helper.h`; they wouldn't need to know the details of our code here.
 *
 * --- Including Local Headers ---
 * Notice we use `#include "helper.h"` with double quotes. This is a signal
 * to the compiler to look for the file in the directory that holds THIS source
 * file first, before searching the system's standard library paths.
 *
 *  - `#include <stdio.h>`: Use angle brackets for system libraries.
 *  - `#include "helper.h"`: Use double quotes for your own project's header files.
 */

#include <stdio.h>
#include "helper.h" // We need to include our own header file.

/**
 * @brief Prints a message to demonstrate a function call from a separate file.
 *
 * This is the DEFINITION of the function that was declared in `helper.h`.
 * It contains the actual block of code that will be executed when the
 * function is called.
 */
void say_hello_from_helper(void)
{
    printf("Hello from the helper module! This message comes from helper.c.\n");
}

main.c

/**
 * @file main.c
 * @brief Part 5, Lesson 31: Using a Makefile and Multiple Source Files
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file demonstrates how to use a function from a separate module
 * (`helper.c`) by including its header file (`helper.h`).
 */

/*
 * =====================================================================================
 * |                      - LESSON: PUTTING IT ALL TOGETHER -                          |
 * =====================================================================================
 *
 * Welcome to our first multi-file project!
 *
 * The goal of this lesson is to see how different C files work together.
 *
 * 1. `main.c` (This file): This is the entry point of our program. It contains
 *    the `main` function. It needs to call a function from our "helper" module.
 *
 * 2. `helper.h` (Header file): This file *declares* the functions our helper
 *    module provides. By including it here (`#include "helper.h"`), we tell
 *    the compiler "Trust me, a function named `say_hello_from_helper` exists
 *    somewhere. Here's what it looks like."
 *
 * 3. `helper.c` (Source file): This file *defines* the `say_hello_from_helper`
 *    function, providing the actual code for it.
 *
 * 4. `Makefile`: This is the instruction manual for the compiler. It tells `cc`
 *    how to compile `main.c` and `helper.c` separately into "object files",
 *    and then how to "link" them together into a single, final executable.
 */

#include <stdio.h>
#include "helper.h" // Include the declarations from our helper module.

/**
 * @brief The main entry point of the program.
 *
 * This program demonstrates linking multiple source files. It calls a function
 * defined in `helper.c`.
 *
 * @return 0 on successful execution.
 */
int main(void)
{
    printf("Message from main.c: Calling a function from another file...\n");

    // This function call is possible because we included `helper.h`.
    // The compiler knows the function's "signature" from the header.
    // The LINKER (part of the compilation process guided by the Makefile)
    // is responsible for connecting this call to the actual function code
    // in `helper.c`.
    say_hello_from_helper();

    printf("Message from main.c: The helper function has completed.\n");

    return 0;
}

/*
 * =====================================================================================
 * |                                 - COMPILATION -                                   |
 * =====================================================================================
 *
 * NOTE: Do NOT compile this file directly with a simple `cc` command.
 *
 * This is a multi-file project. To compile and run it, you must use the
 * `make` utility with the provided `Makefile`.
 *
 * Open your terminal in this directory and run:
 *
 *   `make`
 *
 * Then run the resulting executable:
 *
 *   `./31_project_main`
 *
 * For a detailed explanation, read the comments in the `Makefile`.
 */

The Makefile

The Makefile ties it all together. It uses variables, rules, and phony targets to automate the build process.

# Makefile
# @brief Part 5, Lesson 31: Makefiles for Multi-File Projects
# @author dunamismax
# @date 06-15-2025
#
# This file is the lesson on Makefiles. Read the comments from top to bottom
# to learn how to automate the compilation of complex C projects.

# =====================================================================================
# |                                   - LESSON START -                                  |
# =====================================================================================
#
# Welcome to a pivotal moment in your C journey! Until now, we've worked with
# single source files. While great for learning, real-world applications are almost
# always split into multiple files for organization, reusability, and clarity.
#
# Typing out long `cc` commands for every file becomes tedious and error-prone.
# Imagine a project with 50 files! This is where the `make` utility comes in.
#
# WHAT IS A MAKEFILE?
# A `make` program reads a special file, by default named `Makefile`, to understand
# how to build your project. A Makefile contains a set of RULES. Each rule has
# three parts: a TARGET, its DEPENDENCIES, and a RECIPE.
#
#   target: dependencies
#       <tab>recipe (the command to run)
#
# - TARGET: The file we want to build (e.g., an executable or an object file).
# - DEPENDENCIES: The files the target needs in order to be built.
# - RECIPE: The command(s) to execute to create the target.
#
# IMPORTANT: The lines with recipes MUST start with a TAB character, not spaces!

# --- Part 1: Using Variables ---
#
# To make our Makefile clean and easy to modify, we use VARIABLES.
# It's convention to use all caps for variable names.

# The C compiler we want to use.
CC = cc

# The flags we pass to the compiler. These are the same flags we've been using.
# CFLAGS stands for "C Compiler Flags".
CFLAGS = -Wall -Wextra -std=c17

# The name of the final executable file we want to build.
TARGET = 31_project_main

# --- Part 2: Defining the Rules ---
#
# Now we define the rules for building our project. `make` reads these rules
# and figures out what needs to be compiled or re-compiled.

# The first rule in a Makefile is the default rule. When you just type `make`
# in the terminal, this is the target that `make` will try to build. We want
# it to build our entire project.
#
# This rule says: To make the TARGET (`31_project_main`), you first need
# `main.o` and `helper.o`.
# The recipe then links these two object files together to create the final executable.
$(TARGET): main.o helper.o
	$(CC) $(CFLAGS) -o $(TARGET) main.o helper.o

# This rule says: To make `main.o`, you need `main.c` and `helper.h`.
# If `main.c` or `helper.h` has changed since the last time `main.o` was built,
# `make` will run the recipe. The `-c` flag tells the compiler to COMPILE ONLY, creating
# an "object file" (`.o`) without linking.
main.o: main.c helper.h
	$(CC) $(CFLAGS) -c main.c

# This is the rule for our helper module.
# To make `helper.o`, you need `helper.c` and `helper.h`.
helper.o: helper.c helper.h
	$(CC) $(CFLAGS) -c helper.c

# --- Part 3: Phony Targets ---
#
# Sometimes we want a target that isn't an actual file. For example, a "clean"
# target to delete all the compiled files. These are called PHONY targets.
# We declare them with `.PHONY` to tell `make` that this target name doesn't
# correspond to a file it should expect to exist.

.PHONY: all clean

# A common convention is to have an `all` target that is just another name for
# the default target. It doesn't do anything new but provides a clear command.
all: $(TARGET)

# This rule cleans up our directory.
# The `rm` command removes files. The `-f` flag means "force", so it won't
# complain if the files don't exist.
# We remove the object files (`*.o`) and the final executable (`$(TARGET)`).
clean:
	rm -f $(TARGET) *.o

# =====================================================================================
# |                                    - LESSON END -                                   |
# =====================================================================================
#
# HOW TO USE THIS MAKEFILE:
#
# 1. Open a terminal in the directory containing this Makefile and the .c/.h files.
#
# 2. To build the entire project:
#    `make`
#    (or `make all`)
#
#    You will see the commands from the recipes being executed. An executable
#    named `31_project_main` will be created.
#
# 3. To run the program:
#    - On Linux/macOS:   `./31_project_main`
#    - On Windows (WSL): `./31_project_main`
#
# 4. To clean up all generated files (the executable and object files):
#    `make clean`
#
# Try it! Run `make`, then run the program. Then run `make` again. Notice how
# `make` says everything is "up to date"? Now, modify `helper.c` (e.g., add a
# comment) and run `make` again. See how it only re-compiles what's necessary?
# This is the power of `make`!

How to Compile and Run

Build the project:

make

Run the program:

./31_project_main

Clean up generated files:

make clean

Try it: run make, then run the program. Then run make again. Notice how make says everything is “up to date.” Now modify helper.c (for example, add a comment) and run make again. See how it only re-compiles what changed? That is the power of make.

Key Takeaways

  • Real-world C projects are split into multiple source files for organization.
  • Header files (.h) declare function signatures so other files can use them.
  • Source files (.c) define the actual function implementations.
  • The #include "header.h" directive (with quotes) includes your own headers.
  • A Makefile automates the compile-and-link process so you do not have to type long cc commands by hand.
  • make only re-compiles files that have changed, saving time on large projects.
  • Use make clean to remove generated build artifacts.

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Add a new function to helper.c and helper.h and call it from main.c.
  2. Run make twice. Why does the second run do nothing? Touch helper.c and run it again.
  3. Add a third module with its own .c and .h file and add it to the Makefile.

Linking External Libraries

What you’ll learn: using a library: header files, the linker, and the -l flag, with the math library as the example.

Before you start: Lesson 31.

In our last lesson, we learned how to build a project from multiple source files that WE wrote. But what if we want to use code written by someone else? This is where LIBRARIES come in.

What Is an External Library?

A LIBRARY is a collection of pre-written, pre-compiled code that provides specific functionality. For example, there are libraries for advanced math, graphics, networking, sound, and much more. Using a library saves you from having to “reinvent the wheel.”

A library typically consists of two parts:

  1. HEADER FILES (.h): These contain the function declarations, just like our helper.h did. They tell our compiler WHAT functions are available.
  2. A BINARY LIBRARY FILE (.so on Linux, .dylib on macOS, .dll on Windows): This is the pre-compiled code. It contains the actual function definitions.

The Linker

The LINKER is a crucial part of the compilation process. After the compiler turns your source code into object files, the linker’s job is to connect everything. It resolves the function calls in your code to the function definitions, whether they are in your own object files (like in lesson 31) or in an external library file (like in this lesson).

Full Source

/**
 * @file 32_linking_external_libraries.c
 * @brief Part 5, Lesson 32: Linking External Libraries
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for linking against
 * external, pre-compiled libraries. It explains the core concepts
 * through structured comments and provides a runnable example.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * In our last lesson, we learned how to build a project from multiple source
 * files that WE wrote. But what if we want to use code written by someone else?
 * This is where LIBRARIES come in.
 *
 * WHAT IS AN EXTERNAL LIBRARY?
 * A LIBRARY is a collection of pre-written, pre-compiled code that provides
 * specific functionality. For example, there are libraries for advanced math,
 * graphics, networking, sound, and much more. Using a library saves you from
 * having to "reinvent the wheel."
 *
 * A library typically consists of two parts:
 * 1. HEADER FILES (`.h`): These contain the function declarations, just like
 *    our `helper.h` did. They tell our compiler WHAT functions are available.
 * 2. A BINARY LIBRARY FILE (`.so` on Linux, `.dylib` on macOS, `.dll` on Windows):
 *    This is the pre-compiled code. It contains the actual function definitions.
 *
 * THE LINKER
 * The LINKER is a crucial part of the compilation process. After the compiler
 * turns your source code into object files, the linker's job is to connect
 * everything. It resolves the function calls in your code to the function
 * definitions, whether they are in your own object files (like in lesson 31)
 * or in an external library file (like in this lesson).
 */

// --- Part 1: Including the Header ---

// To use a library, you must first include its header file. The C standard
// library provides a powerful math library. Its header is `<math.h>`.
// This gives us access to declarations for functions like `sqrt()` (square root)
// and `pow()` (power).
#include <stdio.h>
#include <math.h>

// M_PI, the value of Pi, is NOT part of ISO C. Many systems (macOS, and Linux
// in its default GNU mode) define it in <math.h> anyway, but a strict standard
// mode such as `-std=c17` on Linux hides it. Using the #ifndef guard from the
// preprocessor lesson, we define it ourselves only when it is missing, so the
// program compiles everywhere.
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

// --- Part 2: The Main Function ---

int main(void)
{
    // The code below uses functions declared in `<math.h>`.
    // However, including the header only tells the compiler that these functions
    // exist. It doesn't tell the linker WHERE to find the compiled code for them.
    // We'll solve that problem during compilation.

    // --- Using sqrt() ---
    // The `sqrt()` function takes a `double` and returns its square root.
    double number_for_sqrt = 81.0;
    double square_root_result = sqrt(number_for_sqrt);

    printf("Using sqrt(): The square root of %.2f is %.2f.\n",
           number_for_sqrt, square_root_result);

    // --- Using pow() ---
    // The `pow()` function takes two `double` arguments (a base and an exponent)
    // and returns the base raised to the power of the exponent.
    double base = 2.0;
    double exponent = 10.0;
    double power_result = pow(base, exponent);

    printf("Using pow(): %.2f to the power of %.2f is %.2f.\n",
           base, exponent, power_result);

    // --- Using sin() ---
    // Let's try a trigonometric function. `sin()` takes an angle in RADIANS.
    // M_PI is the value of Pi (see the #ifndef guard at the top of the file).
    double angle_radians = M_PI / 2.0; // 90 degrees
    double sin_result = sin(angle_radians);

    printf("Using sin(): The sine of PI/2 radians is %.2f.\n", sin_result);

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * HOW TO COMPILE AND RUN THIS CODE (THE IMPORTANT PART!):
 *
 * Because we are using functions from an external math library, we must explicitly
 * tell the linker to include that library's code in our final executable.
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, with a special flag to link the math library:
 *
 *    `cc -Wall -Wextra -std=c17 -o 32_linking_external_libraries 32_linking_external_libraries.c -lm`
 *
 * THE -lm FLAG
 * This is the key to this lesson. The `-l` flag is used to tell the linker
 * which library to link. The name of the math library is `m` (from its file,
 * which is often `libm.so`). So, `-lm` means "link the math library".
 *
 * CONVENTION: The `-l` flags should always come at the END of your command,
 * after your source files.
 *
 * WHAT HAPPENS IF YOU FORGET `-lm`?
 * Try compiling with: `cc ... -o output 32_linking_external_libraries.c`
 * On Linux you will usually get an "undefined reference to `sqrt`" error (and
 * to `pow`, `sin`). This is the linker telling you, "I see you're calling a
 * function named `sqrt`, but I have no idea where its actual code is!" The
 * `-lm` flag solves this by telling the linker to look inside the math library.
 *
 * On macOS the same command may work anyway: there, the math functions live in
 * the system library that every program is linked with. Keep `-lm` regardless,
 * so your build works on every system.
 *
 * 4. Run the executable:
 *    - On Linux/macOS:   `./32_linking_external_libraries`
 *    - On Windows (WSL): `./32_linking_external_libraries`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 32_linking_external_libraries 32_linking_external_libraries.c -lm
./32_linking_external_libraries

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Use pow and sqrt to compute the distance between two points.
  2. Build without -lm and read the error. On which systems does it still build, and why?
  3. Print the sine of 0, 30, 45 and 90 degrees, converting degrees to radians first.

Advanced Terminal UI

What you’ll learn: full-screen terminal programs with ncurses: setup and cleanup, windows, colors and reading single keys.

Before you start: Lessons 31 and 32.

So far, our programs have been linear: we printf some text, scanf some input, and the text scrolls up and away forever. It’s functional, but not very interactive. Today, we take control of the entire terminal screen.

What Is ncurses?

NCURSES is a powerful external library that allows you to create complex Terminal User Interfaces (TUIs). It gives you precise control over:

  • Cursor position: Move the cursor anywhere on the screen.
  • Text attributes: Display text in bold, underlined, or in color.
  • Windows: Divide the screen into independent sections.
  • Input: Read single keystrokes (like arrow keys) without waiting for Enter.

NCURSES is the foundation for many classic terminal applications, like the text editor vim, the system monitor htop, and many more. This lesson will introduce you to the basic building blocks.

IMPORTANT: This program will take over your terminal screen. It will look different from our previous programs!

Setup and Cleanup

Every ncurses program needs a standard setup and cleanup routine. The lesson’s setup turns on the features it uses:

initscr();
noecho();
cbreak();
keypad(stdscr, TRUE);
  • initscr() starts ncurses and takes over the screen.
  • noecho() stops typed keys from being printed automatically.
  • cbreak() hands each key to the program at once, without waiting for Enter.
  • keypad(stdscr, TRUE) lets the program read special keys such as the arrows.

The endwin() function is CRITICAL. It must be called before your program exits to restore the terminal to its normal, sane state. If you forget this, your terminal prompt might be broken!

The Virtual Screen

NCURSES uses a VIRTUAL SCREEN. When you “print” something, it’s drawn to an in-memory representation of the screen first. Nothing appears on the actual terminal until you call refresh().

Full Source

/**
 * @file 33_advanced_terminal_ui.c
 * @brief Part 5, Lesson 33: Advanced Terminal UI with ncurses
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for creating a rich
 * Terminal User Interface (TUI) using the ncurses library.
 * It explains the core concepts through structured comments and
 * provides a runnable example of their implementation.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * So far, our programs have been linear: we `printf` some text, `scanf` some
 * input, and the text scrolls up and away forever. It's functional, but not
 * very interactive. Today, we take control of the entire terminal screen.
 *
 * WHAT IS NCURSES?
 * NCURSES is a powerful external library that allows you to create complex
 * Terminal User Interfaces (TUIs). It gives you precise control over:
 *  - Cursor position: Move the cursor anywhere on the screen.
 *  - Text attributes: Display text in bold, underlined, or in color.
 *  - Windows: Divide the screen into independent sections.
 *  - Input: Read single keystrokes (like arrow keys) without waiting for Enter.
 *
 * NCURSES is the foundation for many classic terminal applications, like the
 * text editor `vim`, the system monitor `htop`, and many more. This lesson
 * will introduce you to the basic building blocks.
 *
 * IMPORTANT: This program will take over your terminal screen. It will look
 * different from our previous programs!
 */

// To use ncurses, you must include its header file.
#include <ncurses.h>
#include <stdlib.h> // For exit()
#include <unistd.h> // We'll use sleep() for a small delay.

// --- Function Prototypes ---
// Good practice to declare our functions before main.
void initialize_ncurses(void);
void cleanup_ncurses(void);
WINDOW *draw_ui(void);

// --- The Main Function ---

int main(void)
{
    initialize_ncurses();

    WINDOW *info_win = draw_ui();

    // After drawing, we wait for the user to press any key before exiting.
    // getch() is the ncurses function to get a single character of input.
    getch();

    // `newwin` allocated memory for the window, so we release it with
    // `delwin`, just as every `malloc` needs a `free`.
    if (info_win != NULL)
    {
        delwin(info_win);
    }

    cleanup_ncurses();

    return 0;
}

// --- Part 1: Initialization and Cleanup ---
/*
 * Every ncurses program needs a standard setup and cleanup routine.
 */
void initialize_ncurses(void)
{
    // initscr() is the FIRST ncurses function you must call. It determines the
    // terminal type, allocates memory, and effectively "takes over" the screen.
    initscr();

    // noecho() prevents keys pressed by the user from being automatically
    // displayed on the screen. This gives us full control over what appears.
    noecho();

    // cbreak() makes input available to the program immediately, without
    // requiring the user to press Enter.
    cbreak();

    // keypad() enables the reading of function keys like F1, F2, and arrow keys.
    // `stdscr` is the default WINDOW that represents the entire screen.
    keypad(stdscr, TRUE);

    // --- Color Initialization ---
    // To use colors, we must check if the terminal supports them.
    if (has_colors() == FALSE)
    {
        // If not, we have to exit gracefully. endwin() comes FIRST: it restores
        // the terminal to its normal state, so our message is readable.
        endwin();
        fprintf(stderr, "Your terminal does not support color.\n");
        exit(1); // exit() from Lesson 14 ends the whole program right here.
    }

    // If colors are supported, we must start the color system.
    start_color();

    // Now we can define COLOR PAIRS. A pair is a foreground/background combination.
    // We give each pair a number. Pair 0 is reserved for the default terminal colors.
    // init_pair(pair_number, foreground_color, background_color);
    init_pair(1, COLOR_YELLOW, COLOR_BLACK); // Yellow text on a black background
    init_pair(2, COLOR_CYAN, COLOR_BLACK);   // Cyan text on a black background
    init_pair(3, COLOR_WHITE, COLOR_BLUE);   // White text on a blue background
}

/*
 * The `endwin()` function is CRITICAL. It must be called before your program
 * exits to restore the terminal to its normal, sane state. If you forget this,
 * your terminal prompt might be broken!
 */
void cleanup_ncurses(void)
{
    endwin();
}

// --- Part 2: Drawing to the Screen ---
/*
 * NCURSES uses a VIRTUAL SCREEN. When you "print" something, it's drawn to an
 * in-memory representation of the screen first. Nothing appears on the actual
 * terminal until you call `refresh()`.
 *
 * This function returns the window it creates, so `main` can free it with
 * `delwin` when the program is done. It returns NULL if there was no room.
 */
WINDOW *draw_ui(void)
{
    // Clear the screen
    clear();

    // --- Basic Drawing on `stdscr` ---
    // `mvprintw(row, col, "text")` moves the cursor to (row, col) and prints.
    // (0, 0) is the top-left corner.
    mvprintw(0, 0, "Welcome to the NCURSES Interactive Environment!");

    // Let's use our color pairs. `attron` turns an attribute ON.
    attron(COLOR_PAIR(1) | A_BOLD); // Turn on Yellow (Pair 1) and BOLD text.
    mvprintw(2, 2, "This text is Yellow and Bold!");
    attroff(COLOR_PAIR(1) | A_BOLD); // Turn the attributes OFF.

    mvprintw(4, 2, "Normal text again.");

    // The REFRESH command. This flushes the virtual screen buffer and updates
    // the physical terminal to show what we've drawn.
    refresh();

    sleep(2); // Pause for 2 seconds to let the user see the first part.

    // --- Creating a WINDOW ---
    // A WINDOW is a rectangular subsection of the screen that you can draw on
    // independently. This is key for organized UIs.

    int height = 10, width = 60;
    int start_y = 6, start_x = 5;

    // `newwin()` creates a new window. Like `malloc`, it returns NULL when it
    // fails, for example when the terminal is too small to hold the window.
    WINDOW *info_win = newwin(height, width, start_y, start_x);
    if (info_win == NULL)
    {
        mvprintw(6, 2, "The terminal is too small for the window demo. Press any key to exit.");
        refresh();
        return NULL;
    }

    // `box(win, 0, 0)` draws a border around the window using default characters.
    box(info_win, 0, 0);

    // Let's draw inside our new window.
    // We'll use the window-specific version of printw: `wprintw`.
    // But first, let's change the window's color scheme.
    wbkgd(info_win, COLOR_PAIR(3)); // Set background for the window

    // Note: coordinates for drawing are relative to the WINDOW's top-left corner.
    // (1, 1) here is one character down and one right from the window's border.
    mvwprintw(info_win, 1, 1, "This is a new window!");

    // Use a different color for this next part. Attributes belong to a window,
    // so we use `wattron`/`wattroff` on `info_win`. Plain `attron` would
    // change `stdscr` instead and have no effect on the text below.
    wattron(info_win, COLOR_PAIR(2));
    mvwprintw(info_win, 3, 3, "You can draw here without affecting the main screen.");
    mvwprintw(info_win, 5, 3, "Press any key to exit this application.");
    wattroff(info_win, COLOR_PAIR(2));

    // To display the window, we must refresh IT.
    wrefresh(info_win);

    return info_win;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * Just like we used `-lm` for the math library, we need to tell the linker to
 * include the ncurses library. The library's name is `ncurses`.
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, adding the `-lncurses` flag AT THE END:
 *
 *    `cc -Wall -Wextra -std=c17 -o 33_advanced_terminal_ui 33_advanced_terminal_ui.c -lncurses`
 *
 * THE -lncurses FLAG
 * This is the crucial part. `-l` tells the linker to look for a library, and
 * `ncurses` is the name of the library we want. Forgetting this flag will
 * result in "undefined reference" errors for all the ncurses functions like
 * `initscr`, `mvprintw`, etc.
 *
 * 4. Run the executable:
 *    - On Linux/macOS:   `./33_advanced_terminal_ui`
 *    - On Windows:       run it in WSL, where ncurses is available.
 *
 *    Your terminal will clear and show the UI we just created! Press any
 *    key to return to your normal command prompt.
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 33_advanced_terminal_ui 33_advanced_terminal_ui.c -lncurses
./33_advanced_terminal_ui

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Move a @ around the screen with the arrow keys until the user presses q.
  2. Draw a second window with a different color pair.
  3. Show the terminal’s size with getmaxyx, and update it when the window is resized (KEY_RESIZE).

Parsing Data Files

What you’ll learn: parsing a CSV data file into structs with sscanf, checking every line, skipping lines that are too long, and why strtok needs more care.

Before you start: Lessons 12, 14 and 15.

So far, our programs have either been non-persistent or have saved data in a simple, unstructured way. Real-world applications, however, almost always need to read structured data–user profiles, game levels, configuration settings, etc. The process of reading this data and converting it into a useful format (like a struct) is called PARSING.

Today, we will learn how to parse a simple Comma-Separated Values (CSV) file. Each line in the file will represent a single record, with fields separated by commas.

The Goal

We will write a program that reads a file named users.dat. Each line of this file will contain a user’s ID, username, level, and active status. Our program will parse each line and load the data into an array of struct User.

We will explore two primary methods for parsing strings: strtok and sscanf. As you will see, sscanf is often safer and more robust.

sscanf is often the best tool for this job. It’s like scanf, but it reads from a string instead of the keyboard. It’s powerful because it can parse complex patterns, and its return value tells you how many items were successfully assigned, which makes error checking very easy:

int items_scanned = sscanf(line, "%d,%49[^,],%d,%d",
                           &current_user.id,
                           current_user.username,
                           &current_user.level,
                           &current_user.is_active);

%49[^,] reads up to 49 characters that are not a comma, which leaves room for the \0 in the 50-character username. A well-formed line gives 4, so any other result means the line is malformed and is skipped.

One weakness to know about: %d cannot tell you that a number was too big for an int. For numbers you do not trust, read the digits as text and convert them with strtol, which reports the overflow, as Lesson 15 does.

Lines That Do Not Fit

fgets stops when line is full. If a line in the file is longer than that, line holds only its first part, with no \n at the end, and the rest is still waiting in the file. The next fgets would return that leftover as if it were a new line, and it might even look like a valid record. So the loop throws the whole line away before it parses anything:

if (strchr(line, '\n') == NULL && !feof(file))
{
    int ch;

    while ((ch = fgetc(file)) != '\n' && ch != EOF)
    {
        // Discard the rest of the overlong line.
    }
    fprintf(stderr, "Warning: Overlong line skipped.\n");
    if (ch == EOF)
    {
        break; // That was the last line: nothing is left to read.
    }
    continue;
}

The last line of a file may have no \n and still be complete; feof tells us when that is the reason.

For Reference: Parsing with strtok()

strtok is another function for splitting a string. It works by finding a delimiter, replacing it with a null terminator (\0), and returning a pointer to the start of the token.

Why Is It Not Preferred?

  1. It MODIFIES the original string. This can be destructive and surprising.
  2. It is STATEFUL. You call it once with the string, then with NULL for subsequent tokens. This makes the code more complex and means you can’t use it to parse two strings at once (it is not “re-entrant” or thread-safe).

While sscanf is generally better, seeing a strtok implementation is useful as you will encounter it in existing C code.

Example strtok loop:

// Important: `strtok` modifies the string, so we'd need a copy.
// char line_copy[MAX_LINE_LENGTH];
// strcpy(line_copy, line);

char *token = strtok(line, ","); // Get first token
if (token) user.id = (int)strtol(token, NULL, 10); // Lesson 15: avoid atoi

token = strtok(NULL, ","); // Get next token
// `strcpy` would overflow `username` if the token were 50 characters or
// more, so check the length first:
if (token && strlen(token) < sizeof(user.username))
    strcpy(user.username, token);

… and so on. As you can see, it’s more verbose and requires more care. (A complete version would also check strtol’s end pointer, as Lesson 15 does. sscanf with %49[^,] does the length check for us.)

Full Source

/**
 * @file 34_parsing_data_files.c
 * @brief Part 5, Lesson 34: Parsing Structured Data Files
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file serves as the lesson and demonstration for reading and parsing
 * structured data files, like CSVs or configuration files.
 * It explains the core concepts through structured comments and
 * provides a runnable example of their implementation.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * So far, our programs have either been non-persistent or have saved data in a
 * simple, unstructured way. Real-world applications, however, almost always
 * need to read structured data--user profiles, game levels, configuration
 * settings, etc. The process of reading this data and converting it into a
 * useful format (like a `struct`) is called PARSING.
 *
 * Today, we will learn how to parse a simple Comma-Separated Values (CSV) file.
 * Each line in the file will represent a single record, with fields separated
 * by commas.
 *
 * THE GOAL:
 * We will write a program that reads a file named `users.dat`. Each line of
 * this file will contain a user's ID, username, level, and active status.
 * Our program will parse each line and load the data into an array of `struct User`.
 *
 * We will explore two primary methods for parsing strings: `strtok` and `sscanf`.
 * As you will see, `sscanf` is often safer and more robust.
 */

#include <stdio.h>
#include <string.h> // For strchr(), and strtok() in the reference section below

#define MAX_LINE_LENGTH 256
#define MAX_USERS 10

// --- Part 1: The Data Structure ---
// First, we need a struct to hold the data for a single user.
// This structure directly mirrors the format of a line in our data file.
typedef struct
{
    int id;
    char username[50];
    int level;
    int is_active; // 1 for active, 0 for inactive
} User;

// --- Function Prototypes ---
void parse_with_sscanf(FILE *file);
void print_user(const User *user);

// --- The Main Function ---
// Our program will expect the name of the data file as a command-line argument.
int main(int argc, char *argv[])
{
    // A program that needs a file to work should always check for it.
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s <datafile>\n", argv[0]);
        return 1;
    }

    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
    {
        // `perror` is a useful function from <stdio.h> that prints our message
        // followed by a system error message for why the operation failed.
        perror("Error opening file");
        return 1;
    }

    printf("--- Parsing data file using sscanf() ---\n");
    parse_with_sscanf(file);

    fclose(file);
    return 0;
}

// --- Part 2: Parsing with sscanf() ---
/*
 * `sscanf` is often the best tool for this job. It's like `scanf`, but it reads
 * from a string instead of the keyboard. It's powerful because it can parse
 * complex patterns, and its return value tells you how many items were
 * successfully assigned, which makes error checking very easy.
 */
void parse_with_sscanf(FILE *file)
{
    char line[MAX_LINE_LENGTH];
    User users[MAX_USERS];
    int user_count = 0;

    // We read the file line by line using `fgets`. This is safe because it
    // prevents buffer overflows by never storing more than `MAX_LINE_LENGTH`
    // characters (including the final '\0') at a time.
    while (fgets(line, sizeof(line), file) != NULL && user_count < MAX_USERS)
    {
        User current_user;

        // `fgets` stops when `line` is full. If a line in the file is longer
        // than that, `line` holds only its first part (with no '\n' at the
        // end) and the rest is still waiting in the file. The next `fgets`
        // would return that leftover as if it were a new line, and it might
        // even look like a valid record. So we throw the whole line away:
        // read and discard characters up to the newline, as Lesson 17 did
        // for keyboard input. (The last line of a file may have no '\n' and
        // still be complete; `feof` tells us when that is the reason.)
        if (strchr(line, '\n') == NULL && !feof(file))
        {
            int ch;

            while ((ch = fgetc(file)) != '\n' && ch != EOF)
            {
                // Discard the rest of the overlong line.
            }
            fprintf(stderr, "Warning: Overlong line skipped.\n");
            if (ch == EOF)
            {
                break; // That was the last line: nothing is left to read.
            }
            continue;
        }

        // This is the core of the sscanf method. Let's break down the format string:
        // "%d"       - Reads an integer (the ID).
        // ","        - Matches and discards a literal comma.
        // "%49[^,]"  - This is the clever part for reading the username.
        //   `%[...]` is a scanset. It reads characters as long as they are in the set.
        //   `^` negates the set, so `[^,]` reads characters as long as they are NOT a comma.
        //   `49` is a width limit to prevent buffer overflow on `username[50]`.
        // ",%d,%d"   - Reads comma, integer, comma, integer for level and status.
        //
        // CRITICAL: We pass POINTERS to the variables where sscanf should store
        // the data. For integers, we use the address-of operator `&`. For the
        // character array `username`, the name itself decays to a pointer.
        //
        // One weakness to know about: `%d` cannot tell you that a number was
        // too big for an `int` (the result is undefined). For numbers you do
        // not trust, read the digits as text and convert them with `strtol`,
        // which reports the overflow, as Lesson 15 does.
        int items_scanned = sscanf(line, "%d,%49[^,],%d,%d",
                                   &current_user.id,
                                   current_user.username,
                                   &current_user.level,
                                   &current_user.is_active);

        // We expect to scan 4 items. If we don't, the line was malformed.
        if (items_scanned == 4)
        {
            users[user_count] = current_user;
            user_count++;
        }
        else
        {
            fprintf(stderr, "Warning: Malformed line skipped: %s", line);
        }
    }

    // Now, let's print out the data we successfully parsed.
    printf("\nSuccessfully parsed %d user records:\n", user_count);
    for (int i = 0; i < user_count; i++)
    {
        print_user(&users[i]);
    }
}

/**
 * @brief A helper function to print the contents of a User struct.
 * @param user A pointer to the User struct to be printed.
 */
void print_user(const User *user)
{
    // The formatting specifiers `%-5d` and `%-15s` left-align the output
    // in a field of a certain width, creating nice columns.
    printf("  User ID: %-5d | Username: %-15s | Level: %-3d | Active: %s\n",
           user->id,
           user->username,
           user->level,
           user->is_active ? "Yes" : "No"); // Using a ternary operator for clean output.
}

/*
 * =====================================================================================
 * |                    - (For Reference) Parsing with strtok() -                      |
 * =====================================================================================
 *
 * `strtok` is another function for splitting a string. It works by finding a
 * delimiter, replacing it with a null terminator (`\0`), and returning a pointer
 * to the start of the token.
 *
 * WHY IS IT NOT PREFERRED?
 * 1. It MODIFIES the original string. This can be destructive and surprising.
 * 2. It is STATEFUL. You call it once with the string, then with NULL for
 *    subsequent tokens. This makes the code more complex and means you can't
 *    use it to parse two strings at once (it is not "re-entrant" or thread-safe).
 *
 * While `sscanf` is generally better, seeing a `strtok` implementation is useful
 * as you will encounter it in existing C code.
 *
 * Example `strtok` loop:
 *
 *   // Important: `strtok` modifies the string, so we'd need a copy.
 *   // char line_copy[MAX_LINE_LENGTH];
 *   // strcpy(line_copy, line);
 *
 *   char *token = strtok(line, ","); // Get first token
 *   if (token) user.id = (int)strtol(token, NULL, 10); // Lesson 15: avoid atoi
 *
 *   token = strtok(NULL, ","); // Get next token
 *   // `strcpy` would overflow `username` if the token were 50 characters or
 *   // more, so check the length first:
 *   if (token && strlen(token) < sizeof(user.username))
 *       strcpy(user.username, token);
 *
 *   ... and so on. As you can see, it's more verbose and requires more care.
 *   (A complete version would also check `strtol`'s end pointer, as Lesson 15
 *   does. `sscanf` with `%49[^,]` does the length check for us.)
 */

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * This program requires a data file to read. You must create it first.
 *
 * 1. CREATE THE DATA FILE:
 *    In the same directory as this C file, create a new file named `users.dat`.
 *    Copy and paste the following content into it:
 *
 *    101,alpha_coder,15,1
 *    102,bit_wizard,22,1
 *    205,kernel_hacker,45,0
 *    this is a bad line and should be skipped
 *    310,logic_lord,33,1
 *    404,syntax_sorcerer,99,1
 *
 * 2. COMPILE THE C FILE:
 *    Open a terminal and navigate to the directory.
 *    `cc -Wall -Wextra -std=c17 -o 34_parsing_data_files 34_parsing_data_files.c`
 *
 * 3. RUN THE EXECUTABLE:
 *    You must provide the name of the data file as a command-line argument.
 *    - On Linux/macOS:   `./34_parsing_data_files users.dat`
 *    - On Windows (WSL): `./34_parsing_data_files users.dat`
 *
 *    NOTE: this program keeps at most MAX_USERS (10) records and stops reading
 *    after that.
 *
 *    The program will read `users.dat`, parse its contents, print a warning for
 *    the bad line, and then display the structured data it successfully extracted.
 *    A line longer than MAX_LINE_LENGTH - 1 (255) characters is skipped with
 *    its own warning.
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 34_parsing_data_files 34_parsing_data_files.c
./34_parsing_data_files users.dat

Create users.dat first, with the sample lines shown in the source above.

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Add an email field to the data file and to struct User.
  2. Print only the active users, then only users above a level the user gives as an argument.
  3. Write the parsed users back out to a new file in the same format.

Capstone: Text Adventure

What you’ll learn: the capstone: a text adventure that loads its world from a file, links rooms with pointers and runs in an ncurses interface.

Before you start: The whole course, especially Lessons 18, 20, 33 and 34.

Welcome to the final project. This is it.

Every lesson, from printf to pointers, from malloc to Makefiles, has been leading to this. You are about to build a complete, interactive application from the ground up. This project doesn’t introduce many new C features; instead, it challenges you to synthesize everything you’ve already learned.

Concepts You Will Use in This Project

  • Foundational Logic: Variables, if/else, for/while loops, functions.
  • Data Structures: structs to model the game world, enums for clarity.
  • Memory Management: malloc and free to dynamically create the world.
  • Pointers: The entire game world is connected by POINTERS. This is the ultimate demonstration of their power.
  • File I/O: The game world is loaded from an external data file (world.map).
  • Parsing: The world data file is parsed with strtol (Lesson 15) and by walking a char * through each line. Lesson 34 used sscanf; here every field is checked by hand, so a malformed map is rejected with a clear error.
  • Command-Line Arguments: The program takes the map file as an argument.
  • External Libraries: We use the ncurses library for an advanced terminal UI.
  • Build Tooling: Lesson 31 introduced Makefiles, but this capstone stays in one source file so you can build it directly with a compiler command.
  • Advanced Techniques: We’ll even use an array of structs with function pointers for a clean command handling system.

You are no longer a beginner. You are a C developer. Let’s build something awesome.

Robust Input and Display

The game checks its ncurses calls the same way earlier lessons checked scanf and malloc:

  • ui_init refuses a terminal smaller than 40 columns by 10 rows, and checks that each newwin call returned a window.
  • ui_get_input checks wgetnstr. If input has ended, the game loop stops instead of acting on a buffer that was never filled. It also turns echo on while it reads, because noecho() (Lesson 33) would hide what the player types.
  • The status and input windows are 3 rows high, so box() has a row inside its border for the text, and ui_draw erases the input window first, so a long command does not show behind a shorter one.
  • Room descriptions are often wider than the terminal, so they wrap. ui_draw prints each log message after the end of the previous one, rather than at a fixed row, so a wrapped message is never drawn over.

Full Source

/**
 * @file 35_capstone_awesome_text_adventure.c
 * @brief Part 5, Lesson 35: Capstone - Awesome Text Adventure
 * @author dunamismax
 * @date 06-15-2025
 *
 * This file contains the source code for the final capstone lesson.
 * It pulls together many earlier topics into a single ncurses-based
 * text adventure that loads a map file at runtime.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Welcome to the final project. This is it.
 *
 * Every lesson, from `printf` to pointers, from `malloc` to Makefiles, has been
 * leading to this. You are about to build a complete, interactive application
 * from the ground up. This project doesn't introduce many new C features;
 * instead, it challenges you to synthesize everything you've already learned.
 *
 * CONCEPTS YOU WILL USE IN THIS PROJECT:
 * - Foundational Logic: Variables, `if`/`else`, `for`/`while` loops, functions.
 * - Data Structures: `struct`s to model the game world, `enum`s for clarity.
 * - Memory Management: `malloc` and `free` to dynamically create the world.
 * - Pointers: The entire game world is connected by POINTERS. This is the ultimate
 *   demonstration of their power.
 * - File I/O: The game world is loaded from an external data file (`world.map`).
 * - Parsing: The world data file is parsed with `strtol` (Lesson 15) and by
 *   walking a `char *` through each line. Lesson 34 used `sscanf`; here every
 *   field is checked by hand, so a malformed map is rejected with a clear error.
 * - Command-Line Arguments: The program takes the map file as an argument.
 * - External Libraries: We use the `ncurses` library for an advanced terminal UI.
 * - Build Tooling: Lesson 31 introduced Makefiles, but this capstone stays in
 *   one source file so you can build it directly with a compiler command.
 * - Advanced Techniques: We'll even use an array of structs with function
 *   pointers for a clean command handling system.
 *
 * You are no longer a beginner. You are a C developer. Let's build something awesome.
 */

// --- Standard and External Library Includes ---
#include <ctype.h>   // For tolower()
#include <errno.h>   // For robust numeric parsing
#include <limits.h>  // For INT_MIN and INT_MAX
#include <ncurses.h> // For the advanced Terminal User Interface (TUI)
#include <stdio.h>
#include <stdlib.h> // For malloc, free, exit
#include <string.h> // For string manipulation functions

// --- Game Constants and Enums ---
#define MAX_DIRECTIONS 4
#define MAX_ROOMS 100
#define MAX_LOG_MESSAGES 10
#define INPUT_BUFFER_SIZE 100
#define ROOM_DESCRIPTION_SIZE 512
#define WORLD_LINE_BUFFER_SIZE 1024

// Using an enum makes direction-related code much more readable and safe.
typedef enum
{
    NORTH,
    SOUTH,
    EAST,
    WEST
} Direction;

// --- Core Data Structures ---
// These structs are the blueprint for our entire game world.

// Forward declaration is needed because GameState and Room reference each other.
struct GameState;

typedef struct Room
{
    int id;
    char description[ROOM_DESCRIPTION_SIZE];
    // This is the key: an array of POINTERS to other Room structs.
    // This is how we form the "graph" of our world map.
    struct Room *exits[MAX_DIRECTIONS];
} Room;

typedef struct Player
{
    Room *current_room; // A pointer to the room the player is currently in.
} Player;

typedef struct
{
    char *command;
    // A function pointer! This lets us create a clean, data-driven command system.
    void (*handler)(struct GameState *game, char *argument);
} Command;

// The main struct to hold the entire state of our running game.
typedef struct GameState
{
    Player player;
    Room *all_rooms[MAX_ROOMS];
    int num_rooms;
    int game_should_close;

    // For the ncurses UI
    WINDOW *main_win;
    WINDOW *status_win;
    WINDOW *input_win;
    char *log_messages[MAX_LOG_MESSAGES];
    int log_count;
} GameState;

// --- Function Prototypes ---
// Grouping prototypes makes the code easier to navigate.

// Game Lifecycle
void game_loop(GameState *game);
void cleanup(GameState *game);

// World Loading & Parsing
GameState *load_world(const char *filename);
int parse_room(char *line, GameState *game);
int parse_link(char *line, GameState *game);
Room *find_room_by_id(GameState *game, int id);
const char *direction_to_string(Direction d);
int read_world_line(FILE *file, char *buffer, size_t size);
char *skip_whitespace(char *text);
int parse_int_token(char **cursor, int *value);
int has_only_trailing_whitespace(char *text);
char *duplicate_string(const char *text);

// Command Handling
void parse_and_execute_command(GameState *game, char *input);
void handle_quit(GameState *game, char *argument);
void handle_look(GameState *game, char *argument);
void handle_go(GameState *game, char *argument);
void handle_help(GameState *game, char *argument);

// UI Functions (ncurses)
int ui_init(GameState *game);
void ui_draw(GameState *game);
int ui_get_input(GameState *game, char *buffer);
void ui_log(GameState *game, const char *message);
void ui_cleanup(GameState *game);

// --- Parsing Helpers ---
// Small functions used by the world loader below.

int read_world_line(FILE *file, char *buffer, size_t size)
{
    char *newline;

    // `fgets` takes an `int` size; our line buffer is small enough to fit.
    if (fgets(buffer, (int)size, file) == NULL)
    {
        return 0;
    }

    newline = strchr(buffer, '\n');
    if (newline != NULL)
    {
        *newline = '\0';
        return 1;
    }

    if (!feof(file))
    {
        int ch;

        while ((ch = fgetc(file)) != '\n' && ch != EOF)
        {
            // Discard the rest of an overlong line so the next read starts cleanly.
        }
        buffer[0] = '\0';
        return -1;
    }

    return 1;
}

char *skip_whitespace(char *text)
{
    while (isspace((unsigned char)*text))
    {
        text++;
    }

    return text;
}

int parse_int_token(char **cursor, int *value)
{
    char *endptr;
    long parsed;

    *cursor = skip_whitespace(*cursor);
    if (**cursor == '\0')
    {
        return 0;
    }

    errno = 0;
    parsed = strtol(*cursor, &endptr, 10);
    if (errno != 0 || endptr == *cursor || parsed < INT_MIN || parsed > INT_MAX)
    {
        return 0;
    }

    *value = (int)parsed;
    *cursor = endptr;
    return 1;
}

int has_only_trailing_whitespace(char *text)
{
    text = skip_whitespace(text);
    return *text == '\0';
}

char *duplicate_string(const char *text)
{
    size_t length = strlen(text) + 1;
    char *copy = malloc(length);

    if (!copy)
    {
        return NULL;
    }

    memcpy(copy, text, length);
    return copy;
}

// --- Main Program Entry ---
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        // We use fprintf to stderr for error messages.
        fprintf(stderr, "Usage: %s <world_map_file>\n", argv[0]);
        return 1;
    }

    // --- Initialization ---
    // Load the world from the file specified on the command line.
    GameState *game = load_world(argv[1]);
    if (game == NULL)
    {
        // load_world will have already printed an error.
        return 1;
    }

    // Initialize the ncurses interface. It fails if the terminal is too small.
    if (!ui_init(game))
    {
        cleanup(game);
        return 1;
    }

    // Set the player's starting location.
    game->player.current_room = find_room_by_id(game, 0);
    if (game->player.current_room == NULL)
    {
        ui_cleanup(game);
        cleanup(game);
        fprintf(stderr, "Error: Map has no starting room (ID 0).\n");
        return 1;
    }

    // --- Main Game Loop ---
    ui_log(game, "Welcome to the Awesome Text Adventure! Type 'help' for commands.");
    handle_look(game, NULL); // Give the player their initial view.
    game_loop(game);

    // --- Cleanup ---
    // This is crucial for both ncurses and memory management.
    ui_cleanup(game);
    cleanup(game);

    printf("Thank you for playing!\n");
    return 0;
}

// =====================================================================================
// |                            - WORLD LOADING & PARSING -                            |
// =====================================================================================

/**
 * @brief Loads the entire game world from a data file.
 * This function demonstrates dynamic allocation, file I/O, and robust parsing.
 */
GameState *load_world(const char *filename)
{
    // Dynamically allocate the main GameState struct.
    GameState *game = malloc(sizeof(GameState));
    int line_number = 0;
    int line_status;
    if (!game)
        return NULL;
    // ALWAYS initialize allocated memory.
    memset(game, 0, sizeof(GameState));

    FILE *file = fopen(filename, "r");
    if (!file)
    {
        perror("Error opening world file");
        free(game);
        return NULL;
    }

    char line[WORLD_LINE_BUFFER_SIZE];

    // --- TWO-PASS LOADING ---
    // This is a common and robust technique for loading interconnected data.
    // Pass 1: Read all room definitions and allocate memory for them.
    while ((line_status = read_world_line(file, line, sizeof(line))) != 0)
    {
        line_number++;
        if (line_status < 0)
        {
            fprintf(stderr, "Error: world file line %d is too long.\n", line_number);
            fclose(file);
            cleanup(game);
            return NULL;
        }

        if (strncmp(line, "room", 4) == 0)
        {
            if (!parse_room(line, game))
            {
                fprintf(stderr, "Error parsing room definition on line %d.\n", line_number);
                fclose(file);
                cleanup(game);
                return NULL;
            }
        }
    }

    // Go back to the beginning of the file for the second pass. `rewind(file)`
    // does the same but cannot report failure; `fseek` returns non-zero when
    // it fails, as in Lesson 30, so we can stop instead of reading nothing.
    if (fseek(file, 0, SEEK_SET) != 0)
    {
        perror("Error rewinding world file");
        fclose(file);
        cleanup(game);
        return NULL;
    }
    line_number = 0;

    // Pass 2: Read all link definitions and connect the already-created rooms.
    while ((line_status = read_world_line(file, line, sizeof(line))) != 0)
    {
        line_number++;
        if (line_status < 0)
        {
            fprintf(stderr, "Error: world file line %d is too long.\n", line_number);
            fclose(file);
            cleanup(game);
            return NULL;
        }

        if (strncmp(line, "link", 4) == 0)
        {
            if (!parse_link(line, game))
            {
                fprintf(stderr, "Error parsing link definition on line %d.\n", line_number);
                fclose(file);
                cleanup(game);
                return NULL;
            }
        }
    }

    fclose(file);
    return game;
}

/**
 * @brief Parses a 'room' line and creates a Room struct.
 */
int parse_room(char *line, GameState *game)
{
    char *cursor = line;
    if (game->num_rooms >= MAX_ROOMS)
        return 0; // Guard against overflow.

    int id;
    char desc[ROOM_DESCRIPTION_SIZE];
    size_t desc_length = 0;

    if (strncmp(cursor, "room", 4) != 0 || !isspace((unsigned char)cursor[4]))
    {
        return 0;
    }
    cursor += 4;

    if (!parse_int_token(&cursor, &id))
    {
        return 0;
    }

    cursor = skip_whitespace(cursor);
    if (*cursor != '"')
    {
        return 0;
    }
    cursor++;

    while (*cursor != '"' && *cursor != '\0')
    {
        if (desc_length >= sizeof(desc) - 1)
        {
            return 0;
        }

        desc[desc_length++] = *cursor;
        cursor++;
    }

    if (*cursor != '"')
    {
        return 0;
    }

    desc[desc_length] = '\0';
    cursor++;

    if (!has_only_trailing_whitespace(cursor) || find_room_by_id(game, id) != NULL)
    {
        return 0;
    }

    Room *new_room = malloc(sizeof(Room));
    if (!new_room)
        return 0;

    memset(new_room, 0, sizeof(Room)); // Initialize room exits to NULL.
    new_room->id = id;
    memcpy(new_room->description, desc, desc_length + 1);

    game->all_rooms[game->num_rooms++] = new_room;
    return 1;
}

/**
 * @brief Parses a 'link' line and connects two existing rooms.
 */
int parse_link(char *line, GameState *game)
{
    char *cursor = line;
    int from_id, to_id;
    char dir_str[10];
    size_t dir_length = 0;

    if (strncmp(cursor, "link", 4) != 0 || !isspace((unsigned char)cursor[4]))
    {
        return 0;
    }
    cursor += 4;

    if (!parse_int_token(&cursor, &from_id))
    {
        return 0;
    }

    cursor = skip_whitespace(cursor);
    if (*cursor == '\0')
    {
        return 0;
    }

    while (*cursor != '\0' && !isspace((unsigned char)*cursor))
    {
        if (dir_length >= sizeof(dir_str) - 1)
        {
            return 0;
        }

        dir_str[dir_length++] = *cursor;
        cursor++;
    }
    dir_str[dir_length] = '\0';

    if (dir_length == 0 || !parse_int_token(&cursor, &to_id) || !has_only_trailing_whitespace(cursor))
    {
        return 0;
    }

    Room *from_room = find_room_by_id(game, from_id);
    Room *to_room = find_room_by_id(game, to_id);

    if (!from_room || !to_room)
        return 0; // One of the rooms doesn't exist.

    Direction dir;
    if (strcmp(dir_str, "n") == 0)
        dir = NORTH;
    else if (strcmp(dir_str, "s") == 0)
        dir = SOUTH;
    else if (strcmp(dir_str, "e") == 0)
        dir = EAST;
    else if (strcmp(dir_str, "w") == 0)
        dir = WEST;
    else
        return 0; // Invalid direction.

    // This is the magic: we store a POINTER to the 'to' room in the 'from' room's exit array.
    from_room->exits[dir] = to_room;
    return 1;
}

/**
 * @brief A helper function to find a room pointer from its integer ID.
 */
Room *find_room_by_id(GameState *game, int id)
{
    for (int i = 0; i < game->num_rooms; i++)
    {
        if (game->all_rooms[i]->id == id)
        {
            return game->all_rooms[i];
        }
    }
    return NULL; // Not found
}

const char *direction_to_string(Direction d)
{
    switch (d)
    {
    case NORTH:
        return "north";
    case SOUTH:
        return "south";
    case EAST:
        return "east";
    case WEST:
        return "west";
    }
    return "unknown";
}

// =====================================================================================
// |                                - COMMAND HANDLING -                               |
// =====================================================================================

// This array of structs is our command table. It pairs a command string with
// the function pointer that handles it. This is a very clean, scalable design.
Command command_table[] = {
    {"quit", handle_quit},
    {"exit", handle_quit},
    {"look", handle_look},
    {"l", handle_look},
    {"go", handle_go},
    {"north", handle_go},
    {"south", handle_go},
    {"east", handle_go},
    {"west", handle_go},
    {"n", handle_go},
    {"s", handle_go},
    {"e", handle_go},
    {"w", handle_go},
    {"help", handle_help},
    {NULL, NULL} // Sentinel to mark the end of the array.
};

/**
 * @brief Processes the user's raw input string, finds the correct command handler,
 *        and calls it.
 */
void parse_and_execute_command(GameState *game, char *input)
{
    char *verb, *argument;

    // Convert input to lowercase for case-insensitive matching.
    for (int i = 0; input[i]; i++)
    {
        input[i] = (char)tolower((unsigned char)input[i]);
    }

    verb = strtok(input, " \n"); // Tokenize the string by space or newline.
    if (!verb)
        return; // Empty input

    argument = strtok(NULL, " \n");

    // Handle single-word movement commands like "north"
    if (strcmp(verb, "n") == 0 || strcmp(verb, "north") == 0 ||
        strcmp(verb, "s") == 0 || strcmp(verb, "south") == 0 ||
        strcmp(verb, "e") == 0 || strcmp(verb, "east") == 0 ||
        strcmp(verb, "w") == 0 || strcmp(verb, "west") == 0)
    {
        argument = verb; // The argument to "go" is the verb itself.
        verb = "go";
    }

    for (int i = 0; command_table[i].command != NULL; i++)
    {
        if (strcmp(verb, command_table[i].command) == 0)
        {
            // We found a match! Call the associated function pointer.
            command_table[i].handler(game, argument);
            return;
        }
    }

    ui_log(game, "I don't understand that command.");
}

void handle_quit(GameState *game, char *argument)
{
    (void)argument;
    game->game_should_close = 1;
}

void handle_look(GameState *game, char *argument)
{
    (void)argument;
    Room *room = game->player.current_room;
    ui_log(game, room->description);

    // `strcat` does not check sizes, so we made the buffer big enough for the
    // longest possible result: "Exits: north south east west " is 29
    // characters plus the `\0`, well under 100.
    char exits_str[100] = "Exits: ";
    int found_exit = 0;
    for (int i = 0; i < MAX_DIRECTIONS; i++)
    {
        if (room->exits[i])
        {
            // `i` is an `int`; the cast says we mean it as a `Direction`
            // (the enum values are 0 to MAX_DIRECTIONS - 1).
            strcat(exits_str, direction_to_string((Direction)i));
            strcat(exits_str, " ");
            found_exit = 1;
        }
    }
    if (found_exit)
    {
        ui_log(game, exits_str);
    }
    else
    {
        ui_log(game, "There are no obvious exits.");
    }
}

void handle_go(GameState *game, char *argument)
{
    if (!argument)
    {
        ui_log(game, "Go where?");
        return;
    }

    int dir = -1;
    if (strcmp(argument, "n") == 0 || strcmp(argument, "north") == 0)
        dir = NORTH;
    else if (strcmp(argument, "s") == 0 || strcmp(argument, "south") == 0)
        dir = SOUTH;
    else if (strcmp(argument, "e") == 0 || strcmp(argument, "east") == 0)
        dir = EAST;
    else if (strcmp(argument, "w") == 0 || strcmp(argument, "west") == 0)
        dir = WEST;

    if (dir == -1)
    {
        ui_log(game, "That's not a valid direction.");
        return;
    }

    Room *next_room = game->player.current_room->exits[dir];
    if (next_room)
    {
        game->player.current_room = next_room;
        handle_look(game, NULL); // Automatically look after moving.
    }
    else
    {
        ui_log(game, "You can't go that way.");
    }
}

void handle_help(GameState *game, char *argument)
{
    (void)argument;
    ui_log(game, "--- Available Commands ---");
    ui_log(game, "look (l): Describe the current room and exits.");
    ui_log(game, "go <dir>: Move in a direction (north, south, east, west, or n,s,e,w).");
    ui_log(game, "help: Show this help message.");
    ui_log(game, "quit/exit: Leave the game.");
}

// =====================================================================================
// |                                - NCURSES UI CODE -                                |
// =====================================================================================

/**
 * @brief Starts ncurses and creates the game's three windows.
 * @return 1 on success, 0 if the terminal is too small or a window could not
 *         be created (the terminal is restored and an error printed).
 */
int ui_init(GameState *game)
{
    initscr();
    cbreak();
    noecho();
    keypad(stdscr, TRUE);

    int height, width;
    getmaxyx(stdscr, height, width);

    // The layout needs a few rows for the log plus 6 for the status and input
    // windows. On a tinier terminal the window sizes below would be zero or
    // negative, so we stop with a clear message instead.
    if (height < 10 || width < 40)
    {
        endwin();
        fprintf(stderr, "Error: The terminal must be at least 40 columns by 10 rows.\n");
        return 0;
    }

    // Create a main window for game text, a status window, and an input window.
    // The status and input windows are 3 rows each: `box()` draws a border on
    // the top and bottom rows, which leaves the middle row for text.
    // Like `malloc`, `newwin` returns NULL when it fails, so we check all three.
    game->main_win = newwin(height - 6, width, 0, 0);
    game->status_win = newwin(3, width, height - 6, 0);
    game->input_win = newwin(3, width, height - 3, 0);
    if (!game->main_win || !game->status_win || !game->input_win)
    {
        ui_cleanup(game); // delwin() safely ignores the NULL ones.
        fprintf(stderr, "Error: Could not create the game windows.\n");
        return 0;
    }

    scrollok(game->main_win, TRUE); // Allow the main window to scroll.

    refresh();
    return 1;
}

void ui_draw(GameState *game)
{
    // Draw status window. Erase it first, like the other two: printing
    // "Room 1" over "Room 10" would leave the old "0" on screen.
    werase(game->status_win);
    box(game->status_win, 0, 0);
    mvwprintw(game->status_win, 1, 2, "Location: Room %d", game->player.current_room->id);

    // Draw input window. `werase` first clears the last command; `box` only
    // draws the border, so a long command would otherwise still show behind a
    // shorter one.
    werase(game->input_win);
    box(game->input_win, 0, 0);
    mvwprintw(game->input_win, 1, 2, "> ");

    // Draw main window log messages. A room description is often wider than
    // the terminal, so it WRAPS onto the next line. Printing message `i` at a
    // fixed row such as `i + 1` would draw the next message over that wrapped
    // text. Instead we start at row 1 and let each message (ending in "\n")
    // leave the cursor where the next one should begin. Because the window
    // has `scrollok` on, text that runs past the bottom scrolls the oldest
    // lines away, so the newest messages are always visible.
    werase(game->main_win);
    wmove(game->main_win, 1, 0);
    for (int i = 0; i < game->log_count; i++)
    {
        wprintw(game->main_win, "  %s\n", game->log_messages[i]);
    }

    // Refresh all windows to show changes
    wrefresh(game->main_win);
    wrefresh(game->status_win);
    wrefresh(game->input_win);
}

void ui_log(GameState *game, const char *message)
{
    char *message_copy = duplicate_string(message);

    if (!message_copy)
    {
        return;
    }

    // If the log is full, shift all messages up.
    if (game->log_count >= MAX_LOG_MESSAGES)
    {
        free(game->log_messages[0]);
        for (int i = 0; i < MAX_LOG_MESSAGES - 1; i++)
        {
            game->log_messages[i] = game->log_messages[i + 1];
        }
        game->log_count--;
    }

    game->log_messages[game->log_count++] = message_copy;
}

/**
 * @brief Reads one command from the player.
 * @return 1 if a line was read, 0 if input has ended or failed.
 */
int ui_get_input(GameState *game, char *buffer)
{
    // Move cursor to input window and get string from user.
    wmove(game->input_win, 1, 4);

    // `ui_init` called `noecho()` (Lesson 33), so keys are not printed as they
    // are typed. That suits single-key input, but here the player types a whole
    // command and needs to see it, so echo is on just while we read the line.
    echo();

    // Like `scanf` and `fgets`, `wgetnstr` can fail, for example when the
    // terminal goes away. It then returns ERR and may not have written
    // anything into `buffer`, so we must not use the buffer's contents.
    int result = wgetnstr(game->input_win, buffer, INPUT_BUFFER_SIZE - 1);
    noecho();
    if (result == ERR)
    {
        buffer[0] = '\0';
        return 0;
    }
    return 1;
}

void ui_cleanup(GameState *game)
{
    delwin(game->main_win);
    delwin(game->status_win);
    delwin(game->input_win);
    endwin(); // Restore terminal to normal state. CRITICAL.
}

// =====================================================================================
// |                                 - GAME LIFECYCLE -                                |
// =====================================================================================

void game_loop(GameState *game)
{
    char input_buffer[INPUT_BUFFER_SIZE] = "";

    while (!game->game_should_close)
    {
        ui_draw(game);
        if (!ui_get_input(game, input_buffer))
        {
            // No more input can arrive. Without this check the loop would
            // spin forever on the same failed read.
            game->game_should_close = 1;
            break;
        }
        parse_and_execute_command(game, input_buffer);
    }
}

/**
 * @brief Frees all dynamically allocated memory.
 * This is CRITICAL for preventing memory leaks. A C developer must always
 * clean up their own mess.
 */
void cleanup(GameState *game)
{
    // Free all the room structs
    for (int i = 0; i < game->num_rooms; i++)
    {
        free(game->all_rooms[i]);
    }
    // Free all the log message strings
    for (int i = 0; i < game->log_count; i++)
    {
        free(game->log_messages[i]);
    }
    // Finally, free the main GameState struct itself.
    free(game);
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * HOW TO COMPILE AND RUN THIS PROJECT:
 *
 * This lesson is still a single-source-file program. You can compile it with
 * one command, then point it at any compatible map file you create. Because it
 * depends on `ncurses`, it is aimed at Unix-like environments unless you install
 * a compatible curses implementation for your platform.
 *
 * 1. CREATE THE DATA FILE:
 *    In the same directory, create a file named `world.map`. This file defines
 *    the rooms and their connections. Copy this content into it:
 *
 *    room 0 "You are in a dusty, forgotten library. Ancient tomes line the walls. A grand wooden door stands to the north."
 *    room 1 "You've entered a vast, cold cavern. The sound of dripping water echoes around you. A narrow passage leads east."
 *    room 2 "This is a small, cramped tunnel. It smells of damp earth. The path continues west, and you see a faint light to the south."
 *    room 3 "You emerge into a treasure room! Piles of gold and jewels glitter in the torchlight. A heavy stone door is to the north."
 *
 *    link 0 n 1
 *    link 1 s 0
 *    link 1 e 2
 *    link 2 w 1
 *    link 2 s 3
 *    link 3 n 2
 *
 * 2. COMPILE THE PROGRAM:
 *    Open a terminal in the directory containing this file and link `ncurses`:
 *
 *      `cc -Wall -Wextra -std=c17 -o 35_capstone_awesome_text_adventure 35_capstone_awesome_text_adventure.c -lncurses`
 *
 * 3. RUN THE GAME:
 *    Execute the program, passing the map file as a command-line argument:
 *
 *      `./35_capstone_awesome_text_adventure world.map`
 *
 *    Your terminal will transform, and the game will begin.
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 35_capstone_awesome_text_adventure 35_capstone_awesome_text_adventure.c -lncurses
./35_capstone_awesome_text_adventure world.map

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Add a new room to world.map and connect it to the existing ones.
  2. Add an inventory command and an item the player can pick up.
  3. Add a save command that writes the player’s current room to a file, and load it at startup.

Debugging

What you’ll learn: building with debug information, stopping and stepping through a program in gdb or lldb, reading a backtrace, and reading an AddressSanitizer report.

Before you start: The whole course through Lesson 35; Lessons 8, 13 and 22 matter most.

Welcome to Part 6, the Toolsmith Path. You can now write real C programs. This part is about the tools that keep them correct: debuggers, sanitizers and tests.

Until now, when a program misbehaved, the natural move was to add printf calls and run it again. That works, but it is slow: every new question means editing, recompiling and rerunning. A DEBUGGER answers those questions while the program runs. It can stop the program at a line you choose (a BREAKPOINT), run it one line at a time (STEPPING), show the value of any variable, and show the chain of function calls that led to the current line (the BACKTRACE).

The two common debuggers are GDB (usual on Linux and WSL) and LLDB (which macOS ships with the Xcode command line tools). They work the same way; only some command names differ. On Linux, install gdb with sudo apt install gdb.

Build With Debug Information

A debugger needs a map from the machine code back to your source: file names, line numbers and variable names. The -g flag adds this DEBUG INFORMATION. -O0 turns optimization off, so the program runs line by line exactly as you wrote it:

cc -g -O0 -Wall -Wextra -std=c17 -o 36_debugging 36_debugging.c

The lesson’s program analyzes a week of temperature readings. As written, it is correct:

int readings[DAYS] = {18, 21, 19, 24, 22, 17, 20};

int total = sum_readings(readings, DAYS);
int highest = highest_reading(readings, DAYS);
double average = average_reading(readings, DAYS);

A Debugging Session

Start the program under the debugger (gdb ./36_debugging or lldb ./36_debugging) and type commands at its prompt:

What you wantGDBLLDB
Stop when a function startsbreak sum_readingsb sum_readings
Start the programrunrun
Run the next linenextnext
Go into the function called on this linestepstep
Print a variableprint totalp total
Show every local variableinfo localsframe variable
Show the chain of callsbacktracebt
Run until this function returnsfinishfinish
Stop whenever a variable changeswatch totalwatchpoint set variable total
Keep running to the next breakpointcontinuecontinue
Leave the debuggerquitquit

Try it: break sum_readings, run, then next and print total a few times to watch the total grow. backtrace shows two FRAMES, sum_readings called by main; finish shows the return value, 141. continue stops in sum_readings again, because average_reading calls it too, and now the backtrace has three frames.

A backtrace is most useful when a program crashes: run it in the debugger, and when it stops, backtrace shows the line that crashed (frame #0) and how the program got there.

Catching the Hidden Bug

sum_readings has a bug you can switch on with -DSHOW_BUG (conditional compilation, Lesson 22). It makes the loop stop at index count instead of count - 1, the classic OFF-BY-ONE error, so the last pass reads one element past the end of the array:

#ifdef SHOW_BUG
    int last = count;
#else
    int last = count - 1; // The last valid index.
#endif

That is undefined behavior (Lesson 8). The program may print a wrong total or, by luck, the right one, and it never says anything is wrong. A SANITIZER is a checker the compiler builds into your program. ADDRESSSANITIZER (ASan, -fsanitize=address) checks every memory access and stops the program at the first bad one:

cc -g -O0 -Wall -Wextra -std=c17 -DSHOW_BUG -fsanitize=address -o 36_debugging_bug 36_debugging.c
./36_debugging_bug

Shortened, its report looks like this (addresses and line numbers differ):

==12345==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffc...
READ of size 4 at 0x7ffc... thread T0
    #0 0x... in sum_readings 36_debugging.c:<line>
    #1 0x... in main 36_debugging.c:<line>
...
    [32, 60) 'readings' <== Memory access at offset 60 overflows this variable

Read it from the top: the kind of error (an overflow of an array on the stack), what happened (a READ of 4 bytes, one int), the backtrace (frame #0, sum_readings, is where it happened), and the variable it went past, readings.

Full Source

/**
 * @file 36_debugging.c
 * @brief Part 6, Lesson 36: Debugging
 * @author dunamismax
 * @date 11-20-2026
 *
 * This file teaches how to find bugs with tools instead of guesswork: building
 * with debug information, pausing and stepping through a program in a
 * DEBUGGER (gdb or lldb), reading a BACKTRACE, and reading the report a
 * SANITIZER prints when it catches a memory error.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Welcome to Part 6, the Toolsmith Path. You can now write real C programs.
 * This part is about the tools that keep them correct: debuggers, sanitizers
 * and tests.
 *
 * Until now, when a program misbehaved, the natural move was to add `printf`
 * calls and run it again. That works, but it is slow: every new question means
 * editing, recompiling and rerunning. A DEBUGGER answers those questions while
 * the program runs. It can:
 *
 * - stop the program at a line you choose (a BREAKPOINT),
 * - run it one line at a time (STEPPING),
 * - show the value of any variable at that moment,
 * - show the chain of function calls that led to the current line (the
 *   BACKTRACE, also called the call stack).
 *
 * The two common debuggers are GDB (the GNU debugger, usual on Linux and WSL)
 * and LLDB (the LLVM debugger, the one macOS ships with the Xcode command line
 * tools). They work the same way; only some command names differ. On Linux,
 * install gdb with `sudo apt install gdb` (or your system's package manager).
 *
 * STEP 1: BUILD WITH DEBUG INFORMATION
 *
 * A debugger needs a map from the machine code back to your source: file
 * names, line numbers and variable names. The `-g` flag adds this DEBUG
 * INFORMATION. The `-O0` flag turns optimization off, so the program runs
 * line by line exactly as you wrote it (an optimized program can skip lines or
 * keep a variable only in a register, which makes stepping confusing):
 *
 *    cc -g -O0 -Wall -Wextra -std=c17 -o 36_debugging 36_debugging.c
 *
 * The program below analyzes a week of temperature readings. As written, it
 * is correct. Later in the lesson you will switch on a hidden bug and catch it
 * with a sanitizer.
 */

#include <stdio.h>

#define DAYS 7

// --- Function Prototypes ---
int sum_readings(const int readings[], int count);
int highest_reading(const int readings[], int count);
double average_reading(const int readings[], int count);

// --- Part 1: The Program We Will Debug ---

/**
 * @brief Adds up `count` readings.
 */
int sum_readings(const int readings[], int count)
{
    int total = 0;

    // The loop bound is where the hidden bug lives. Compiling with
    // `-DSHOW_BUG` defines the macro SHOW_BUG, and conditional compilation
    // (Lesson 22) then picks the buggy line instead of the correct one.
#ifdef SHOW_BUG
    // THE BUG: the last valid index of an array of `count` elements is
    // `count - 1`, but this version stops at `count`, so the final pass reads
    // `readings[count]`, one element past the end. This is the classic
    // OFF-BY-ONE error, the same mistake as writing `i <= count` in the loop.
    int last = count;
#else
    int last = count - 1; // The last valid index.
#endif
    for (int i = 0; i <= last; i++)
    {
        total += readings[i];
    }
    return total;
}

/**
 * @brief Returns the largest of `count` readings. `count` must be at least 1.
 */
int highest_reading(const int readings[], int count)
{
    int highest = readings[0];
    for (int i = 1; i < count; i++)
    {
        if (readings[i] > highest)
        {
            highest = readings[i];
        }
    }
    return highest;
}

/**
 * @brief Returns the average of `count` readings. `count` must be at least 1.
 */
double average_reading(const int readings[], int count)
{
    return (double)sum_readings(readings, count) / count;
}

int main(void)
{
    int readings[DAYS] = {18, 21, 19, 24, 22, 17, 20};

    int total = sum_readings(readings, DAYS);
    int highest = highest_reading(readings, DAYS);
    double average = average_reading(readings, DAYS);

    printf("Readings for %d days\n", DAYS);
    printf("Total:   %d\n", total);
    printf("Highest: %d\n", highest);
    printf("Average: %.2f\n", average);

    return 0;
}

/*
 * --- Part 2: A Debugging Session ---
 *
 * Build the program with `-g -O0` as shown above, then start it under the
 * debugger. Each line below is one command you type at the debugger's prompt:
 * `(gdb)` or `(lldb)`.
 *
 *    gdb ./36_debugging              lldb ./36_debugging
 *
 *    WHAT YOU WANT                   GDB                    LLDB
 *    Stop when a function starts     break sum_readings     b sum_readings
 *    Start the program               run                    run
 *    Run the next line               next                   next
 *    Go INTO the function called     step                   step
 *      on this line
 *    Print a variable                print total            p total
 *    Print an array element          print readings[i]      p readings[i]
 *    Show every local variable       info locals            frame variable
 *    Show the chain of calls         backtrace              bt
 *    Run until this function         finish                 finish
 *      returns
 *    Stop whenever a variable        watch total            watchpoint set
 *      changes                                                variable total
 *    Keep running until the next     continue               continue
 *      breakpoint
 *    Leave the debugger              quit                   quit
 *
 * Try this session:
 *
 * 1. `break sum_readings`, then `run`. The program stops at the first line of
 *    `sum_readings`, BEFORE that line runs.
 * 2. `next` a few times and `print total` after each one. Watch `total` grow
 *    by one reading per pass of the loop.
 * 3. `backtrace`. You will see two FRAMES: `sum_readings` on top, called by
 *    `main` below it. Each frame lists its arguments, so you can see that
 *    `count` is 7.
 * 4. `finish` runs to the end of `sum_readings` and shows its return value,
 *    141.
 * 5. `continue`. The program stops in `sum_readings` again, because
 *    `average_reading` calls it too. `backtrace` now shows three frames:
 *    `sum_readings`, `average_reading`, `main`.
 * 6. `quit`.
 *
 * A backtrace is most useful when a program CRASHES. Run a crashing program
 * under the debugger and, when it stops with the error, type `backtrace`: the
 * top frame is the line that crashed, and the frames below it are how the
 * program got there.
 */

/*
 * --- Part 3: Catching the Hidden Bug ---
 *
 * Now build the program with the bug switched on:
 *
 *    cc -g -O0 -Wall -Wextra -std=c17 -DSHOW_BUG -o 36_debugging_bug 36_debugging.c
 *    ./36_debugging_bug
 *
 * Reading past the end of an array is UNDEFINED BEHAVIOR (Lesson 8). The total
 * and average may come out wrong, or they may look right by luck. You cannot
 * trust either result, and that is exactly what makes this kind of bug
 * dangerous: the program does not tell you anything is wrong.
 *
 * A SANITIZER is a checker the compiler builds into your program. ADDRESSSANITIZER
 * (ASan) checks every memory access while the program runs and stops it at the
 * first bad one. Turn it on with `-fsanitize=address`:
 *
 *    cc -g -O0 -Wall -Wextra -std=c17 -DSHOW_BUG -fsanitize=address -o 36_debugging_bug 36_debugging.c
 *    ./36_debugging_bug
 *
 * (ASan works with Clang and GCC on Linux and WSL, and with Clang on macOS.)
 * The program now stops with a report. Shortened, it looks like this; the
 * addresses and line numbers will differ on your machine:
 *
 *    ==12345==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffc...
 *    READ of size 4 at 0x7ffc... thread T0
 *        #0 0x... in sum_readings 36_debugging.c:<line>
 *        #1 0x... in main 36_debugging.c:<line>
 *    ...
 *      This frame has 1 object(s):
 *        [32, 60) 'readings' <== Memory access at offset 60 overflows this variable
 *
 * HOW TO READ IT:
 *
 * - The first line names the kind of error: a STACK-BUFFER-OVERFLOW is an
 *   access past the end of an array that lives on the stack (a local
 *   variable).
 * - "READ of size 4" says the program READ 4 bytes, one `int`.
 * - The numbered lines are a BACKTRACE, exactly like the debugger's: frame #0
 *   is where the bad read happened, `sum_readings`, with its file and line
 *   (thanks to `-g`), and frame #1 is `main`, which called it.
 * - The last part names the variable: the read went just past the end of
 *   `readings`.
 *
 * Always read a sanitizer report from the top, and look at frame #0 first.
 * Lesson 37 meets ASan's partner, UndefinedBehaviorSanitizer.
 */

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  Build with `-g -O0` when you debug: `-g` adds DEBUG INFORMATION and `-O0`
 *     keeps the program in the order you wrote it.
 * 2.  A DEBUGGER (gdb or lldb) can stop at a BREAKPOINT, step line by line,
 *     print variables and show the BACKTRACE of calls that led to a line.
 * 3.  When a program crashes, run it in the debugger and type `backtrace`:
 *     frame #0 is the line that crashed.
 * 4.  A memory bug may produce no visible symptom. `-fsanitize=address`
 *     (ASAN) stops the program at the first bad access and reports where it
 *     happened and which variable it hit.
 * 5.  Read sanitizer reports from the top: the error kind, then frame #0.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal. On Windows, use the Ubuntu terminal of WSL.
 * 2. Navigate to the directory where you saved this file.
 * 3. Compile it with debug information:
 *    `cc -g -O0 -Wall -Wextra -std=c17 -o 36_debugging 36_debugging.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./36_debugging`
 *    - On Windows (WSL): `./36_debugging`
 * 5. Debug it: `gdb ./36_debugging` on Linux and WSL, `lldb ./36_debugging` on macOS.
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 36_debugging 36_debugging.c
./36_debugging

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Set a breakpoint in highest_reading and use print highest (or p highest in lldb) after each pass of its loop. On which pass does it change to 24?
  2. Use a watchpoint on total in sum_readings and continue until it stops seven times. What values does total take?
  3. Switch on the bug with -DSHOW_BUG and build it without a sanitizer. Run it a few times: is the total wrong? Then build it with -fsanitize=address and find the line number of the bad read in the report.

Undefined Behavior

What you’ll learn: what undefined behavior is, why optimizing compilers make it dangerous, the common kinds (signed overflow, out-of-bounds access, uninitialized reads, bad shifts, strict aliasing, unsequenced changes) and the safe way to write each.

Before you start: Lessons 8, 13, 21 and 36.

The C standard describes what every valid program does. For some operations it says the opposite: if a program does this, the standard places NO requirements at all on what happens. That is UNDEFINED BEHAVIOR (UB). You have met it already: reading past the end of an array (Lesson 8) and using memory after free (Lesson 13).

“No requirements” is meant literally. The program may crash, print garbage, or work perfectly today and fail after a compiler upgrade. Worse, OPTIMIZING compilers ASSUME that undefined behavior never happens. A check such as if (x + 1 < x) (“did x + 1 overflow?”) can be deleted entirely when x is a signed int: the condition could only be true through an overflow, overflow “cannot happen”, so the compiler may treat it as always false.

So the rule is not “UB usually works out”. The rule is: never let it happen.

Signed Integer Overflow

Going past INT_MAX or INT_MIN (from <limits.h>) is SIGNED INTEGER OVERFLOW, and it is undefined behavior. UNSIGNED arithmetic is different: it is defined to WRAP AROUND, which Lesson 28’s hash function relies on. The safe way to add two ints is to check first, using only operations that cannot overflow themselves:

if ((b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b))
{
    return false;
}
*result = a + b;
return true;

Out-of-Bounds Access and Uninitialized Variables

Reading or writing outside an array is undefined behavior, even one element past the end. Check an index before using it whenever it comes from outside your own loop:

if (index < 0 || index >= count)
{
    return false;
}

Using the value of a local variable that was never set is undefined behavior too. That is why every lesson since Lesson 3 initializes its variables. -Wall warns about many of these reads, and MemorySanitizer (-fsanitize=memory, Clang on Linux) catches them at run time.

Shifts

Shifting by a negative amount, by the width of the type or more (1u << 32 when an unsigned int has 32 bits), or shifting a negative value left is undefined. Shift unsigned values, and check the amount first:

int width = (int)(sizeof(unsigned int) * CHAR_BIT);
if (bit < 0 || bit >= width)
{
    return false;
}
*result = 1u << bit;

Strict Aliasing

C lets you look at an object only through its own type, or as raw bytes. Reading a float through a uint32_t *, as in uint32_t bits = *(uint32_t *)&value;, breaks this STRICT ALIASING rule, and the compiler may reorder or drop the read. To copy an object’s bits into another type, use memcpy, which copies bytes and is always allowed:

memcpy(&bits, &value, sizeof(bits));

Unsequenced Modifications

Changing a variable twice in one expression, as in i = i++ + 1;, or changing it and reading it elsewhere in the same expression, is undefined: nothing says which part happens first. Write one change per statement. -Wall warns about these.

Unspecified and Implementation-Defined Behavior

The standard leaves some things open on purpose, under three names, and only the first is dangerous. UNDEFINED BEHAVIOR has no requirements at all. UNSPECIFIED BEHAVIOR allows several outcomes and the compiler may pick any: in printf("%d %d\n", first(), second()), either function may run first. IMPLEMENTATION-DEFINED BEHAVIOR is unspecified behavior that each compiler documents: the size of an int, whether a plain char is signed, what shifting a negative number right gives. Such a program is correct but may act differently elsewhere. Lesson 23’s union read is an example: C allows reading the int member after storing a double, but the number depends on how the machine stores the two types.

Watching UBSan Catch It

UNDEFINEDBEHAVIORSANITIZER (UBSan, -fsanitize=undefined) checks for many of these while the program runs. Building the lesson with -DSHOW_UB adds a real signed overflow:

int counter = INT_MAX;
counter = counter + 1; // UNDEFINED BEHAVIOR: signed overflow.
cc -g -Wall -Wextra -std=c17 -DSHOW_UB -fsanitize=undefined -o 37_ub 37_undefined_behavior.c
./37_ub

UBSan names the file, line and column, and the values involved: “signed integer overflow: 2147483647 + 1 cannot be represented in type ‘int’”. Without the sanitizer the program says nothing, and its result cannot be trusted.

Full Source

/**
 * @file 37_undefined_behavior.c
 * @brief Part 6, Lesson 37: Undefined Behavior
 * @author dunamismax
 * @date 11-20-2026
 *
 * This file is a tour of UNDEFINED BEHAVIOR: what the C standard means by it,
 * why it is more dangerous than an ordinary bug, the most common kinds
 * (signed overflow, out-of-bounds access, uninitialized reads, bad shifts,
 * strict aliasing, unsequenced changes), the safe way to write each one, and
 * how UndefinedBehaviorSanitizer catches them at run time.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * The C standard describes what every valid program does. For some operations
 * it says the opposite: if a program does this, the standard places NO
 * requirements at all on what happens. That is UNDEFINED BEHAVIOR (UB). You
 * have met it already: reading past the end of an array (Lesson 8) and using
 * memory after `free` (Lesson 13).
 *
 * "No requirements" is meant literally. The program may crash, print garbage,
 * or work perfectly today and fail after a compiler upgrade or on another
 * machine. Worse, OPTIMIZING compilers ASSUME that undefined behavior never
 * happens and draw conclusions from that. A check such as
 *
 *    if (x + 1 < x)   // "did x + 1 overflow?"
 *
 * can be deleted entirely when `x` is a signed `int`: `x + 1 < x` could only
 * be true if the addition overflowed, overflow "cannot happen", so the
 * compiler may treat the condition as always false.
 *
 * So the rule is not "UB usually works out". The rule is: never let it
 * happen. This lesson shows the common kinds and the safe way to write each
 * one. UNDEFINEDBEHAVIORSANITIZER (UBSan, `-fsanitize=undefined`) catches many
 * of them while the program runs; Part 7 of this file shows it in action.
 */

#include <limits.h>  // INT_MAX, INT_MIN and CHAR_BIT
#include <stdbool.h> // bool, true and false
#include <stdint.h>  // uint32_t, an unsigned type of exactly 32 bits
#include <stdio.h>
#include <string.h> // memcpy

// --- Function Prototypes ---
bool checked_add(int a, int b, int *result);
bool element_at(const int values[], int count, int index, int *result);
bool bit_mask(int bit, unsigned int *result);

// --- Part 1: Signed Integer Overflow ---

/*
 * An `int` has a largest value, INT_MAX, and a smallest, INT_MIN (from
 * <limits.h>; 2147483647 and -2147483648 on every common machine). Going past
 * either one is SIGNED INTEGER OVERFLOW, and it is undefined behavior.
 *
 * UNSIGNED types are different: their arithmetic is defined to WRAP AROUND,
 * so `UINT_MAX + 1` is 0. Lesson 28's hash function relies on that.
 *
 * The safe way to add two `int`s is to check BEFORE adding whether the result
 * would fit, using only operations that cannot overflow themselves.
 */

/**
 * @brief Adds `a` and `b` into `*result` if the sum fits in an `int`.
 * @return true on success, false (leaving `*result` alone) if it would overflow.
 */
bool checked_add(int a, int b, int *result)
{
    // With a positive `b`, the sum is too big exactly when `a > INT_MAX - b`.
    // With a negative `b`, it is too small exactly when `a < INT_MIN - b`.
    // Neither subtraction can overflow: `b` has the sign that moves the limit
    // back toward zero.
    if ((b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b))
    {
        return false;
    }
    *result = a + b;
    return true;
}

// --- Part 2: Out-of-Bounds Access ---

/*
 * Reading or writing outside an array is undefined behavior, even one element
 * past the end. Lesson 36 showed AddressSanitizer catching it. The safe
 * habit is to check an index before using it whenever it comes from outside
 * your own loop: from the user, a file or another function.
 */

/**
 * @brief Copies `values[index]` into `*result` if `index` is valid.
 */
bool element_at(const int values[], int count, int index, int *result)
{
    if (index < 0 || index >= count)
    {
        return false;
    }
    *result = values[index];
    return true;
}

// --- Part 3: Uninitialized Variables ---

/*
 * A local variable that has not been given a value holds whatever bytes were
 * in that memory before. Using its value is undefined behavior:
 *
 *    int count;
 *    printf("%d\n", count);   // WRONG: count was never set
 *
 * This is why every lesson since Lesson 3 initializes its variables (`int
 * user_age = 0;`). `-Wall` warns about many of these reads, and
 * MemorySanitizer (`-fsanitize=memory`, Clang on Linux) catches them at run
 * time.
 */

// --- Part 4: Shifts ---

/*
 * Shifting (Lesson 21) has three undefined cases: shifting by a negative
 * amount, shifting by the width of the type or more (`1u << 32` when an
 * `unsigned int` has 32 bits), and shifting a negative signed value left.
 * Shift unsigned values, and check the amount first.
 */

/**
 * @brief Stores a mask with only bit `bit` set in `*result`, if `bit` is valid.
 */
bool bit_mask(int bit, unsigned int *result)
{
    // The number of bits in an `unsigned int`: its size in bytes times
    // CHAR_BIT, the bits in a byte (8). The product is small, so it fits in
    // an `int`; the cast says so.
    int width = (int)(sizeof(unsigned int) * CHAR_BIT);
    if (bit < 0 || bit >= width)
    {
        return false;
    }
    *result = 1u << bit;
    return true;
}

// --- Part 5: Strict Aliasing ---

/*
 * C lets you look at an object only through its own type (or a compatible
 * one), or as raw bytes through `unsigned char`. Reading a `float` through a
 * `uint32_t *` breaks this STRICT ALIASING rule:
 *
 *    float value = 1.0f;
 *    uint32_t bits = *(uint32_t *)&value;   // WRONG: undefined behavior
 *
 * The compiler may assume a `uint32_t *` never points at a `float` and
 * reorder or drop the read. The safe way to copy an object's bits into
 * another type is `memcpy`, which copies bytes and is always allowed. Main
 * does exactly that below. (Compilers turn such a small `memcpy` into a
 * single move instruction, so it costs nothing.)
 */

// --- Part 6: Unsequenced Modifications ---

/*
 * Changing a variable twice in one expression, or changing it and reading it
 * elsewhere in the same expression, is undefined behavior:
 *
 *    i = i++ + 1;          // WRONG
 *    printf("%d %d\n", i, i++);   // WRONG
 *
 * There is no rule saying which part happens first. Write one change per
 * statement. `-Wall` warns about these (`-Wunsequenced` in Clang,
 * `-Wsequence-point` in GCC).
 */

// --- Not Everything Left Open Is Undefined ---

/*
 * The standard leaves some things open on purpose, and it has three names for
 * them. Only the first is dangerous:
 *
 * - UNDEFINED BEHAVIOR: no requirements at all. Everything above.
 *
 * - UNSPECIFIED BEHAVIOR: the standard allows several outcomes and the
 *   compiler may pick any of them, each time, without saying which. The order
 *   in which a call's arguments are worked out is one: in
 *   `printf("%d %d\n", first(), second())`, either function may run first.
 *   Every choice gives a valid program; just do not depend on one of them.
 *
 * - IMPLEMENTATION-DEFINED BEHAVIOR: unspecified behavior where each compiler
 *   must document the choice it makes. The size of an `int`, whether a plain
 *   `char` is signed, and the result of shifting a negative number right are
 *   examples. The program is correct, but it may behave differently with
 *   another compiler or on another machine.
 *
 * Lesson 23 met an example. It stored a `double` in a union and then read the
 * `int` member. C allows that: the double's bytes are read as an int. But
 * which number comes out depends on how the compiler and machine store the
 * two types, and the standard leaves that to the implementation. On every
 * machine this course runs on, where any bit pattern is a valid `int`, that
 * is not undefined, but it is not portable either.
 */

int main(void)
{
    printf("--- Part 1: Signed Integer Overflow ---\n");
    int sum = 0;
    if (checked_add(2000000000, 100, &sum))
    {
        printf("2000000000 + 100 = %d\n", sum);
    }
    if (!checked_add(2000000000, 2000000000, &sum))
    {
        printf("2000000000 + 2000000000 would overflow an int, so it was refused.\n");
    }

    printf("\n--- Part 2: Out-of-Bounds Access ---\n");
    int values[] = {10, 20, 30, 40};
    int count = 4;
    int element = 0;
    if (element_at(values, count, 2, &element))
    {
        printf("values[2] = %d\n", element);
    }
    if (!element_at(values, count, 5, &element))
    {
        printf("Index 5 is outside an array of %d elements, so it was refused.\n", count);
    }

    printf("\n--- Part 4: Shifts ---\n");
    unsigned int mask = 0;
    if (bit_mask(3, &mask))
    {
        printf("bit_mask(3) = %u\n", mask);
    }
    if (!bit_mask(40, &mask))
    {
        printf("bit_mask(40) was refused: an unsigned int has only %d bits here.\n",
               (int)(sizeof(unsigned int) * CHAR_BIT));
    }

    printf("\n--- Part 5: Strict Aliasing ---\n");
    float value = 1.0f;
    uint32_t bits = 0;
    // Copy only if the two types really are the same size (they are on every
    // common machine), so memcpy can never write past the end of `bits`.
    if (sizeof(value) == sizeof(bits))
    {
        memcpy(&bits, &value, sizeof(bits));
        // `unsigned long` holds at least 32 bits, so it can print any uint32_t.
        printf("The bits of 1.0f are 0x%08lX.\n", (unsigned long)bits);
    }

    // --- Part 7: Watching UBSan Catch Undefined Behavior ---
    //
    // This block is compiled only when you build with `-DSHOW_UB` (conditional
    // compilation, Lesson 22). It overflows an `int` on purpose:
    //
    //    cc -g -Wall -Wextra -std=c17 -DSHOW_UB -fsanitize=undefined -o 37_ub 37_undefined_behavior.c
    //    ./37_ub
    //
    // UBSan prints a line like
    //
    //    37_undefined_behavior.c:<line>:<column>: runtime error: signed integer
    //    overflow: 2147483647 + 1 cannot be represented in type 'int'
    //
    // naming the file, line and column of the overflow. Without
    // `-fsanitize=undefined` the program says nothing, and whatever it prints
    // for the result cannot be trusted.
#ifdef SHOW_UB
    int counter = INT_MAX;
    counter = counter + 1; // UNDEFINED BEHAVIOR: signed overflow.
    printf("\nINT_MAX + 1 gave %d\n", counter);
#endif

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  UNDEFINED BEHAVIOR means the C standard places no requirements on what
 *     happens. "It worked when I tried it" proves nothing.
 * 2.  Optimizing compilers assume UB never happens, so they can remove checks
 *     that only make sense if it did.
 * 3.  Signed overflow is UB; unsigned arithmetic wraps around. Check before
 *     adding, as `checked_add` does.
 * 4.  Check indexes before using them, initialize every variable, and keep
 *     shift amounts between 0 and the type's width minus one.
 * 5.  Use `memcpy` to copy an object's bits into another type, never a
 *     pointer cast (STRICT ALIASING).
 * 6.  Change a variable at most once per expression.
 * 7.  Build with `-fsanitize=address,undefined` while developing, and turn
 *     on warnings: the compiler and the sanitizers catch most of these.
 * 8.  Unspecified and implementation-defined behavior are not bugs, but a
 *     program that depends on them may act differently elsewhere. Only
 *     undefined behavior has no rules at all.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal. On Windows, use the Ubuntu terminal of WSL.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 37_undefined_behavior 37_undefined_behavior.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./37_undefined_behavior`
 *    - On Windows (WSL): `./37_undefined_behavior`
 * 5. Then build it with `-DSHOW_UB -fsanitize=undefined` (see Part 7) and watch
 *    UBSan report the overflow.
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 37_undefined_behavior 37_undefined_behavior.c
./37_undefined_behavior

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Write bool checked_multiply(int a, int b, int *result) that refuses products that do not fit in an int. Test it with values near INT_MAX and with negative numbers.
  2. Build the lesson with -DSHOW_UB once with -O0 and once with -O2, without the sanitizer. Does the printed result change? Why can it?
  3. Add a bad shift such as 1 << 40 behind its own #ifdef, build with -fsanitize=undefined, and read UBSan’s report.

Testing in C

What you’ll learn: unit tests without a framework: assert, a CHECK macro that counts failures, exit codes for scripts and CI, edge cases, and the #define main trick for testing another program’s functions.

Before you start: Lessons 22, 36 and 37.

Every lesson in this course is checked automatically: a script compiles it, feeds it input and compares what it prints with what it should print. That is TESTING, and it is how you know code still works after you change it.

A UNIT TEST checks one small piece of code, usually one function, on chosen inputs whose correct answers you already know: “clamp(15, 0, 10) must be 10”. Many languages ship a testing library; in C you can go a long way with a few lines of your own. The lesson tests three small functions: clamp, count_words and is_palindrome.

assert: Stating What Must Be True

assert(condition) from <assert.h> checks a condition while the program runs. If it is false, the program prints the condition, the file and the line, and stops at once. Use it for things that can only be false if the PROGRAM has a bug, never for bad user input:

assert(low <= high);

Compiling with -DNDEBUG removes every assert, so never put code that must run inside one.

A Tiny Test Harness

A TEST HARNESS is the code that runs tests and reports the results. The lesson’s is two counters and one macro:

#define CHECK(condition)                                            \
    do                                                              \
    {                                                               \
        checks_run++;                                               \
        if (!(condition))                                           \
        {                                                           \
            checks_failed++;                                        \
            printf("FAILED (line %d): %s\n", __LINE__, #condition); \
        }                                                           \
    } while (0)
  • #condition (the STRINGIZING operator) turns the argument into a string, so a failure shows the check exactly as written.
  • __LINE__ is replaced by the line number where the macro is used.
  • do { ... } while (0) makes the macro’s statements act like one statement, so it works after an if like any other statement.

Unlike assert, a failed CHECK does not stop the program, so one run reports every failure.

Edge Cases

Good tests check the ordinary case and the EDGE CASES, the inputs at the boundaries where bugs hide:

CHECK(count_words("hello world") == 2);
CHECK(count_words("") == 0);
CHECK(count_words("   ") == 0);
CHECK(count_words("  leading and trailing  ") == 3);

Exit Status

main returns 0 when every check passed and 1 otherwise. Shells, Makefiles and CI services read that EXIT STATUS, not the text. Try ./38_testing; echo $?.

Testing Another Program’s Functions

To test functions in a file that has its own main, such as Lesson 20’s linked list, rename that main before including the file:

int lesson_20_main(void); // A prototype for the renamed main.
#define main lesson_20_main
#include "../Part 3 - The Advanced Path_ Towards Mastery/20_linked_lists.c"
#undef main

The included main becomes lesson_20_main, which nobody calls, and the test file supplies the real main. The repository does exactly this in tests/test_linked_list.c and tests/test_hash_table.c (Lesson 28), and the course’s own checks compile and run them on every change.

Full Source

/**
 * @file 38_testing.c
 * @brief Part 6, Lesson 38: Testing in C
 * @author dunamismax
 * @date 11-20-2026
 *
 * This file teaches how to test C code without any framework: `assert` for
 * conditions that must never be false, a tiny CHECK macro that counts
 * failures, exit codes that tell scripts whether the tests passed, and the
 * `#define main` trick for testing the functions of another program.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Every lesson in this course is checked automatically: a script compiles it,
 * feeds it input and compares what it prints with what it should print. That
 * is TESTING, and it is how you know code still works after you change it.
 *
 * A UNIT TEST checks one small piece of code, usually one function, on chosen
 * inputs whose correct answers you already know: "clamp(15, 0, 10) must be
 * 10". When you later change `clamp`, the tests tell you at once if you broke
 * it. Many languages ship a testing library; in C you can go a long way with
 * a few lines of your own.
 *
 * This lesson has three small functions to test, a CHECK macro, a test
 * function for each, and a `main` that runs them all.
 */

#include <assert.h>  // assert
#include <ctype.h>   // isspace
#include <stdbool.h> // bool, true and false
#include <stdio.h>
#include <string.h> // strlen

// --- Function Prototypes ---
int clamp(int value, int low, int high);
int count_words(const char *text);
bool is_palindrome(const char *text);
void test_clamp(void);
void test_count_words(void);
void test_is_palindrome(void);

// --- Part 1: The Code Under Test ---

/*
 * ASSERT: STATING WHAT MUST BE TRUE
 *
 * `assert(condition)` from <assert.h> checks a condition while the program
 * runs. If it is false, the program prints the condition, the file and the
 * line, and stops at once (with `abort`). Use it for things that can only be
 * false if the PROGRAM has a bug, such as a function being called with
 * arguments that make no sense. It is not for bad user input: input errors
 * deserve a friendly message, not a crash.
 *
 * Compiling with `-DNDEBUG` ("no debug") removes every `assert`, so never
 * put code that must run inside one.
 */

/**
 * @brief Limits `value` to the range `low` to `high`.
 */
int clamp(int value, int low, int high)
{
    // Asking for a range whose low end is above its high end is a bug in
    // the caller, so it is an assert, not an error message.
    assert(low <= high);

    if (value < low)
    {
        return low;
    }
    if (value > high)
    {
        return high;
    }
    return value;
}

/**
 * @brief Counts the words in `text`: runs of characters that are not spaces,
 * tabs or newlines.
 */
int count_words(const char *text)
{
    int words = 0;
    bool in_word = false;

    for (size_t i = 0; text[i] != '\0'; i++)
    {
        // `isspace` needs a value that fits in `unsigned char` (or EOF), so the
        // character is converted first; a negative `char` would be undefined
        // behavior (Lesson 37).
        if (isspace((unsigned char)text[i]))
        {
            in_word = false;
        }
        else if (!in_word)
        {
            in_word = true; // The first character of a new word.
            words++;
        }
    }
    return words;
}

/**
 * @brief Returns true if `text` reads the same forwards and backwards.
 */
bool is_palindrome(const char *text)
{
    size_t length = strlen(text);
    if (length == 0)
    {
        return true;
    }

    // Compare the first character with the last, the second with the second
    // to last, and so on, moving inward until the two positions meet.
    size_t left = 0;
    size_t right = length - 1;
    while (left < right)
    {
        if (text[left] != text[right])
        {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

// --- Part 2: A Tiny Test Harness ---

/*
 * A TEST HARNESS is the code that runs tests and reports the results. Ours is
 * two counters and one macro.
 *
 * CHECK(condition) counts one check, and if `condition` is false it counts a
 * failure and prints which check failed and on which line. Three preprocessor
 * features (Lesson 22) make this work:
 *
 * - `#condition` (the STRINGIZING operator) turns the macro's argument into a
 *   string, so the failure message shows the check exactly as you wrote it.
 * - `__LINE__` is replaced by the line number where the macro is used.
 * - `do { ... } while (0)` makes the macro's several statements act like ONE
 *   statement, so `if (x) CHECK(y); else ...` works as it looks. The loop runs
 *   exactly once.
 *
 * The backslash at the end of each line continues the macro onto the next.
 * Unlike `assert`, a failed CHECK does not stop the program, so one run
 * reports every failure.
 */

static int checks_run = 0;
static int checks_failed = 0;

#define CHECK(condition)                                            \
    do                                                              \
    {                                                               \
        checks_run++;                                               \
        if (!(condition))                                           \
        {                                                           \
            checks_failed++;                                        \
            printf("FAILED (line %d): %s\n", __LINE__, #condition); \
        }                                                           \
    } while (0)

// --- Part 3: The Tests ---

/*
 * Good tests check the ordinary case AND the EDGE CASES, the inputs at the
 * boundaries where bugs hide: values exactly at a limit, empty strings, one
 * character, extra spaces.
 */

void test_clamp(void)
{
    CHECK(clamp(5, 0, 10) == 5);   // Inside the range: unchanged.
    CHECK(clamp(-3, 0, 10) == 0);  // Below: raised to the low end.
    CHECK(clamp(15, 0, 10) == 10); // Above: lowered to the high end.
    CHECK(clamp(0, 0, 10) == 0);   // Exactly at each end.
    CHECK(clamp(10, 0, 10) == 10);
    CHECK(clamp(7, 7, 7) == 7); // A range of one value.
}

void test_count_words(void)
{
    CHECK(count_words("hello world") == 2);
    CHECK(count_words("") == 0);
    CHECK(count_words("   ") == 0);
    CHECK(count_words("one") == 1);
    CHECK(count_words("  leading and trailing  ") == 3);
    CHECK(count_words("tabs\tand\nnewlines") == 3);
}

void test_is_palindrome(void)
{
    CHECK(is_palindrome("racecar"));
    CHECK(is_palindrome("abba"));
    CHECK(is_palindrome("a"));
    CHECK(is_palindrome(""));
    CHECK(!is_palindrome("ab"));
    CHECK(!is_palindrome("Racecar")); // Case matters: 'R' is not 'r'.
}

// --- Part 4: Running the Tests ---

/*
 * `main` runs every test function and reports a summary. Its EXIT STATUS is
 * the important part: 0 means every check passed, anything else means a
 * failure. Shells, Makefiles and CI services read that number, not the text.
 * Try `./38_testing; echo $?` to see it.
 */

int main(void)
{
    test_clamp();
    test_count_words();
    test_is_palindrome();

    if (checks_failed > 0)
    {
        printf("%d of %d checks FAILED.\n", checks_failed, checks_run);
        return 1;
    }
    printf("All %d checks passed.\n", checks_run);
    return 0;
}

/*
 * --- Part 5: Testing Another Program's Functions ---
 *
 * The functions above live in the same file as their tests. Often you want
 * to test functions in a file that already has its own `main`, such as
 * Lesson 20's linked list. Compiling the two files together fails: a program
 * can have only one `main`.
 *
 * The preprocessor has a trick for this. Rename the other file's `main`
 * before including it:
 *
 *    int lesson_20_main(void);   // a prototype for the renamed main
 *    #define main lesson_20_main
 *    #include "20_linked_lists.c"
 *    #undef main
 *
 *    int main(void)
 *    {
 *        Node *head = NULL;
 *        insert_at_beginning(&head, 1);
 *        ...
 *    }
 *
 * Every `main` inside the included file becomes `lesson_20_main`, which
 * nobody calls, and the test file supplies the real `main`. The repository
 * does exactly this in `tests/test_linked_list.c` (Lesson 20) and
 * `tests/test_hash_table.c` (Lesson 28); the course's own checks compile and
 * run them on every change.
 *
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Key Takeaways:
 *
 * 1.  A UNIT TEST runs one function on inputs whose answers you know and
 *     checks the results. Test the EDGE CASES, not just the ordinary ones.
 * 2.  `assert` stops the program when something that must be true is false.
 *     Use it for programmer mistakes, never for user input, and remember that
 *     `-DNDEBUG` removes it.
 * 3.  A CHECK macro built from `#condition`, `__LINE__` and `do { } while (0)`
 *     records failures and keeps going, so one run reports them all.
 * 4.  Return 0 from `main` when every test passes and non-zero otherwise:
 *     scripts and CI read the exit status.
 * 5.  `#define main other_name` before an `#include` lets a test file use the
 *     functions of a program that has its own `main`.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal. On Windows, use the Ubuntu terminal of WSL.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the C compiler, `cc`, to create an executable file:
 *    `cc -Wall -Wextra -std=c17 -o 38_testing 38_testing.c`
 * 4. Run the executable and print its exit status:
 *    - On Linux/macOS:   `./38_testing; echo $?`
 *    - On Windows (WSL): `./38_testing; echo $?`
 */

How to Compile and Run

cc -Wall -Wextra -std=c17 -o 38_testing 38_testing.c
./38_testing

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Break clamp on purpose (swap low and high in one return) and run the tests. Do the failure messages point you to the bug? Then fix it.
  2. Write int count_vowels(const char *text) and tests for it, including the empty string and a string with no vowels.
  3. Add a test of your own to tests/test_linked_list.c, for example one for an insert_at_end function you write for Lesson 20.

Glossary

The key terms the lessons introduce, in the UPPERCASE the lesson comments use when a term first appears. Each entry links to the lesson that teaches it.

A

  • Address: The number that identifies a location in memory. Every variable lives at an address, which & gives you and %p prints. (Lesson 10)
  • Address-of operator (&): Gives the memory address of a variable, as in &user_age. scanf needs it so it knows where to store what it reads. (Lesson 3)
  • AddressSanitizer (ASan): A sanitizer, turned on with -fsanitize=address, that stops a program at its first out-of-bounds access, use after free or similar memory error and reports where it happened. (Lesson 36)
  • argc and argv: The two parameters of main that receive command-line arguments: the argument count, and an array of the arguments as strings. argv[0] is the program’s name. (Lesson 15)
  • Argument: A value passed to a function when it is called. In calculate_damage(20, 8), 20 and 8 are the arguments. (Lesson 7)
  • Array: A fixed-size, numbered sequence of elements of the same type, stored next to each other in memory. (Lesson 8)
  • Arrow operator (->): Reaches a struct member through a pointer: p->gpa means (*p).gpa. (Lesson 12)
  • Assertion (assert): A check from <assert.h> that stops the program if a condition that must be true is false. Compiling with -DNDEBUG removes it. (Lesson 38)
  • Atomic operation: An operation that happens as one indivisible step, so no other thread can see it half done. count++ is not atomic. (Lesson 30)

B

  • Backtrace: The chain of function calls that led to the current line, innermost first. Also called the call stack. (Lesson 36)
  • Base case: The condition that stops a recursive function from calling itself again. Without one, recursion never ends. (Lesson 19)
  • Binary library file: The compiled code of a library (.so on Linux, .dylib on macOS) that the linker connects to your program. (Lesson 32)
  • Bit: A single binary digit, 0 or 1. A byte is 8 bits. (Lesson 21)
  • Bitmask: A value whose bits select other bits, used with &, | and ^ to set, clear, test or toggle flags. (Lesson 21)
  • Bitwise operators: Operators that work on the individual bits of integers: &, |, ^, ~, << and >>. (Lesson 21)
  • Blocking call: A function that waits until something happens, such as accept() waiting for a client to connect. (Lesson 26)
  • Breakpoint: A place where a debugger pauses the program, such as the start of a function. (Lesson 36)
  • Buffer: A block of memory that holds data on its way somewhere, such as a char array that fgets reads a line into. (Lesson 9)
  • Buffer overflow: Writing past the end of a buffer. It corrupts other memory and is a classic source of crashes and security holes. (Lesson 9)

C

  • Callback: A function passed (as a function pointer) to another function, which calls it to do part of its work. (Lesson 18)
  • Cast: An explicit conversion to another type, written (type)value, as in (double)a / b. (Lesson 4)
  • Character literal: A single character in single quotes, such as 'A'. Its type is int, and it fits in a char. (Lesson 2)
  • Child process: The new process that fork() creates. It starts as a copy of its parent. (Lesson 29)
  • Client-server model: A design where a server waits for requests and clients connect to it to make them. (Lesson 26)
  • Collision: Two different keys hashing to the same bucket of a hash table. (Lesson 28)
  • Compiler: The program that translates C source code into machine code your computer can run. In this course it is cc: GCC or Clang. (Lesson 1)
  • Conditional compilation: Using #if, #ifdef and #ifndef to include or leave out code before compiling, for example debug output. (Lesson 22)
  • Conditional statement: Code that runs only when a condition is true: if, else if and else. (Lesson 5)
  • const: A promise that something will not be changed. A const char * parameter means the function only reads the string; the compiler rejects code that would change it. (Lesson 16)
  • Critical section: Code that touches shared data and must be run by only one thread at a time, usually guarded by a mutex. (Lesson 30)

D

  • Dangling pointer: A pointer to memory that has been freed. Using it is undefined behavior, which is why lessons set pointers to NULL after free. (Lesson 13)
  • Data type: What kind of value a variable holds, and so how much memory it needs and what you can do with it: int, double, char and so on. (Lesson 2)
  • Debug information: The map from machine code back to source files, lines and variable names that -g adds, so a debugger and sanitizers can name them. (Lesson 36)
  • Debugger: A program, such as gdb or lldb, that runs your program under its control so you can pause it, step through it and inspect its variables. (Lesson 36)
  • Declaration: Introducing a name and its type to the compiler, as in int player_score;. A function declaration is its prototype. (Lesson 2)
  • Definition: The part that actually creates something: a function with its body, or a variable with its storage. (Lesson 7)
  • Dereference: Following a pointer to the value it points to, with *: *p_score is the int that p_score points at. (Lesson 10)
  • Doubly linked list: A linked list whose nodes point both to the next node and to the previous one. (Lesson 25)
  • Dynamic memory allocation: Requesting memory while the program runs, with malloc (and realloc), and giving it back with free. (Lesson 13)

E

  • Edge case: An input at the boundary of what code handles, such as an empty string or a value exactly at a limit. Bugs hide there, so code must handle them and tests should cover them. (Lesson 16)
  • Enum: A type made of named integer constants, such as SUCCESS and FAILURE, so code uses names instead of magic numbers. (Lesson 23)
  • EOF: “End of file”: the special negative value input functions return when there is no more input. Ctrl+D sends it from a terminal. (Lesson 3)
  • Escape sequence: A backslash code inside a string or character literal for a character you cannot type directly, such as \n (newline). (Lesson 1)
  • Exit status: The number main returns to the operating system: 0 for success, anything else for failure. Scripts and CI read it. (Lesson 38)
  • extern: Declares a global variable that is defined in another source file, so this file can use it. (Lesson 24)

F

  • Fall-through: In a switch, running on into the next case because the one before had no break. Almost always a bug. (Lesson 16)
  • feof() and ferror(): Report what earlier reads from a stream found: feof is true once a read reached the end, ferror once a read failed. They tell why fgets stopped, or why a line has no '\n'. (Lesson 17)
  • File descriptor: A small integer the operating system uses to identify an open file or socket. (Lesson 26)
  • FILE pointer: The FILE * that fopen returns and every stdio file function takes. Always check it for NULL. (Lesson 14)
  • Floating-point: Numbers with a fractional part, stored as float or double. This course prefers double. (Lesson 2)
  • fork(): The POSIX system call that creates a new process. It returns 0 in the child and the child’s ID in the parent. (Lesson 29)
  • Format specifier: A placeholder such as %d, %f, %c or %s that tells printf or scanf what type of value goes there. (Lesson 2)
  • Function: A named block of code that does one task, can take parameters and can return a value. (Lesson 7)
  • Function pointer: A variable that holds the address of a function, so the function to call can be chosen at run time. (Lesson 18)

H

  • Hash function: A function that turns a key into an array index for a hash table. (Lesson 28)
  • Hash table: A data structure that maps keys to values, using a hash function to find each key’s bucket quickly. (Lesson 28)
  • Header file: A .h file of declarations (function prototypes, types, macros) that other files #include. (Lesson 31)
  • Header guard: The #ifndef NAME / #define NAME / #endif wrapper that stops a header from being included twice. Also called an include guard. (Lesson 22)
  • Heap: The pool of memory that malloc hands out. Memory there lives until you free it. (Lesson 13)

I

  • Implementation-defined behavior: Behavior the standard leaves open and each compiler must document, such as the size of an int or whether char is signed. Correct, but not portable. (Lesson 37)
  • Index: The position of an element in an array. C counts from 0. (Lesson 8)
  • inet_ntop() and inet_pton(): Convert an IP address between its text form (“presentation”, such as 127.0.0.1) and the binary form a socket address holds (“network”). (Lesson 26)
  • Infinite loop: A loop whose condition never becomes false, so it never ends. (Lesson 6)
  • Initialization: Giving a variable its first value, ideally when you declare it: int number_of_lives = 3;. (Lesson 2)
  • Input buffer: Where typed input waits until a program reads it. Characters scanf does not use, such as a newline, stay there for the next read. (Lesson 3)
  • Integer division: Dividing two integers in C, which throws away the fractional part: 10 / 3 is 3. (Lesson 4)
  • Integer promotion: C widening small types such as char or uint8_t to int before doing arithmetic or bitwise operations on them. (Lesson 21)
  • Iteration: One run through the body of a loop. (Lesson 6)

L

  • Linkage: Whether a name can be seen from other source files. static at file scope gives internal linkage: private to its file. (Lesson 24)
  • Linked list: A chain of nodes, each holding data and a pointer to the next node. It can grow and shrink one node at a time. (Lesson 20)
  • Linker: The tool that joins object files and libraries into one program, connecting each function call to its definition. (Lesson 31)
  • Logical operators: && (and), || (or) and ! (not), which combine or invert true/false values. (Lesson 4)

M

  • Macro: A name that the preprocessor replaces with text before compiling, made with #define. (Lesson 22)
  • Main function: main, where every C program starts running. Its return value is the program’s exit code. (Lesson 1)
  • Makefile: The file make reads: rules saying how to build each target from its dependencies. (Lesson 31)
  • Member: One of the named fields inside a struct, reached with . or ->. (Lesson 12)
  • Memory leak: Memory that was allocated and never freed. A long-running program that leaks keeps growing. (Lesson 13)
  • Modulus (%): The remainder of an integer division: 10 % 3 is 1. (Lesson 4)
  • Mutex: A lock that only one thread can hold at a time, used to protect shared data from race conditions. (Lesson 30)

N

  • NaN (not a number): A special floating-point value, which strtod makes from the text nan. Every comparison with a NaN is false, so test that a value is inside a range (x >= 0.0 && x <= 4.0), not that it is outside one. (Lesson 17)
  • ncurses: A library for full-screen terminal programs: cursor movement, colors, windows and single-key input. (Lesson 33)
  • Network byte order: The byte order (big-endian) that network protocols use. htons converts a port number to it. (Lesson 26)
  • Node: One element of a linked list or tree: some data plus one or more pointers to other nodes. (Lesson 20)
  • NULL: A pointer value that points nowhere. Functions such as malloc and fopen return it to report failure. (Lesson 10)
  • Null terminator: The '\0' character that marks the end of a C string. (Lesson 9)

O

  • Off-by-one error: A loop or index that goes one step too far or stops one step short, such as using <= where < was needed. (Lesson 36)
  • Operator precedence: The rules for which operator is applied first, as in math: 5 + 2 * 10 is 25. Parentheses override them. (Lesson 4)

P

  • Parameter: A variable in a function’s definition that receives the value of an argument. (Lesson 7)
  • Parent process: The process that called fork(). It usually waits for its child with waitpid(). (Lesson 29)
  • Parsing: Turning text, such as a line of a data file, into structured values like the members of a struct. (Lesson 34)
  • Pointer: A variable that holds a memory address. int *p is a pointer to an int. (Lesson 10)
  • Pointer arithmetic: Adding to or subtracting from a pointer to move between array elements: p + 1 points at the next element. (Lesson 11)
  • Port: A number that, with an IP address, identifies one program’s network endpoint on a machine. (Lesson 26)
  • POSIX: The standard for Unix-like operating systems (Linux, macOS) that defines APIs such as fork, sockets and pthreads. Lessons 26, 29 and 30 use it; 27 and 28 are plain ISO C. (Lesson 26)
  • Preprocessor: The first stage of compiling, which handles lines starting with #: includes, macros and conditional compilation. (Lesson 22)
  • Preprocessor directive: A line starting with #, such as #include <stdio.h>, handled by the preprocessor before compiling. (Lesson 1)
  • Process: A running program, with its own memory. fork() creates a new one. (Lesson 29)
  • Prototype: A function’s declaration: its return type, name and parameter types, ending in a semicolon. It lets you call a function defined later. (Lesson 7)

R

  • Race condition: A bug where the result depends on how threads happen to interleave, such as two threads both updating a counter and one update being lost. (Lesson 30)
  • realloc: Resizes a block from malloc, copying its contents if it has to move. On failure it returns NULL and leaves the old block alone. (Lesson 25)
  • Recursion: A function calling itself on a smaller version of its problem until it reaches a base case. (Lesson 19)
  • Relational operators: ==, !=, <, >, <= and >=, which compare two values and give 1 (true) or 0 (false). (Lesson 4)
  • Return value: The value a function sends back to its caller with return. (Lesson 7)

S

  • Sanitizer: A checker the compiler builds into a program (-fsanitize=...) that reports certain bugs while it runs. (Lesson 36)
  • Separate chaining: Handling hash collisions by keeping a linked list of entries in each bucket. (Lesson 28)
  • Shell: A program that reads commands and runs them, such as bash or zsh. (Lesson 29)
  • Signed integer overflow: Going past the largest or smallest value of a signed type such as int. It is undefined behavior, unlike unsigned arithmetic, which wraps around. (Lesson 37)
  • snprintf(): Like printf, but writes into a buffer of a given size and never past its end; text that does not fit is cut short. The safe way to build a string. (Lesson 9)
  • SO_REUSEADDR: A socket option, set with setsockopt() before bind(), that lets a server bind its port again at once instead of waiting for the old connection’s TIME_WAIT to end. (Lesson 26)
  • Socket: An endpoint for network communication, used like a file descriptor with send and recv. (Lesson 26)
  • Stack: The memory that holds a function’s local variables. It is freed automatically when the function returns. (Lesson 13)
  • Stack overflow: Running out of stack memory, typically from recursion that never stops. (Lesson 19)
  • Statement: One instruction in C, usually ending with a semicolon. (Lesson 1)
  • static: Inside a function, makes a local variable keep its value between calls. At file scope, makes a name private to its file. (Lesson 24)
  • Strict aliasing: The rule that an object may only be accessed through its own type (or as raw bytes). Use memcpy to copy an object’s bits into another type. (Lesson 37)
  • String: In C, an array of char ending with a null terminator. (Lesson 9)
  • String literal: Text in double quotes, such as "Hello, World!\n". The compiler adds the null terminator. (Lesson 1)
  • Stringizing operator (#): In a macro, #name turns the argument into a string literal, so a test can print the check exactly as written. (Lesson 38)
  • Struct: A user-defined type that groups related variables, possibly of different types, under one name. (Lesson 12)
  • switch: A statement that jumps to the case matching a whole-number value, or to default; break leaves it. (Lesson 16)

T

  • Test harness: The code that runs tests and reports the results, such as lesson 38’s CHECK macro and its counters. (Lesson 38)
  • Thread: A path of execution inside a process. Threads of one process share its memory. (Lesson 30)
  • TIME_WAIT: The minute or two after a TCP connection closes during which the operating system keeps its port reserved, so late packets are not mistaken for a new connection. (Lesson 26)
  • typedef: Gives a type a new name, as in typedef struct { ... } Student;, so it can be written Student instead of struct Student. (Lesson 17)

U

  • Undefined behavior: Code whose result the C standard does not define, such as reading past the end of an array. Anything can happen, including appearing to work. (Lesson 8)
  • UndefinedBehaviorSanitizer (UBSan): A sanitizer, turned on with -fsanitize=undefined, that reports undefined behavior such as signed overflow and bad shifts while the program runs. (Lesson 37)
  • Union: A type whose members share the same memory, so it holds only one of them at a time. (Lesson 23)
  • Unit test: A test of one small piece of code, usually one function, on inputs whose correct results you already know. (Lesson 38)
  • Unspecified behavior: Behavior where the standard allows several outcomes and the compiler may pick any, such as the order in which a call’s arguments are evaluated. (Lesson 37)

V

  • Variable: A named piece of memory that holds a value of a given type. (Lesson 2)
  • Virtual screen: The in-memory copy of the screen that ncurses draws into. refresh() copies it to the real terminal. (Lesson 33)

W

  • Watchpoint: A debugger setting that pauses the program whenever a chosen variable changes. (Lesson 36)