Skip to content

Part 1 · Lesson 7

Functions

On this page

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

7_functions.c 168 lines Download View on GitHub
/**
 * @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 GCC compiler to create an executable file:
 *    `gcc -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

Runs the lesson in Compiler Explorer (GCC 16.2), nothing to install.

Once, before your first lesson

Install Apple's command line tools. They include the cc compiler: xcode-select --install

New to the terminal? The setup guide walks through it.

Build

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

Run

$ ./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.

Solutions

One worked solution for each exercise above, with the reasoning in its comments. They stay closed until you open them: have a go first, then compare.

Show the solution to exercise 1
1_square.c 46 lines View on GitHub
/**
 * @file 1_square.c
 * @brief Lesson 7, Exercise 1: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Write `int square(int n)` and use it to print the squares of 1 to 10.
 */

#include <stdio.h>

// --- Function Prototypes ---
int square(int n);

int main(void)
{
    for (int i = 1; i <= 10; i++)
    {
        // The call `square(i)` is replaced by the value the function
        // returns, so it can be used directly as a `printf` argument.
        printf("%2d squared is %3d\n", i, square(i));
    }

    return 0;
}

/**
 * @brief Returns n multiplied by itself.
 */
int square(int n)
{
    // `n` is the function's own copy of the argument. On the first call it
    // holds 1, on the next 2, and so on; `main`'s `i` is never touched.
    return n * n;
}

/*
 * The loop and the calculation are now separate jobs: `main` decides WHICH
 * numbers to square, and `square` knows HOW. To print the squares of 1 to
 * 20 you change only the loop; to print cubes you change only the function.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 1_square 1_square.c
 *   ./1_square
 */
Show the solution to exercise 2
2_max_of.c 66 lines View on GitHub
/**
 * @file 2_max_of.c
 * @brief Lesson 7, Exercise 2: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Write `int max_of(int a, int b)` and use it twice to find the largest of
 * three numbers.
 */

#include <stdio.h>

// --- Function Prototypes ---
int max_of(int a, int b);

int main(void)
{
    int first = 12;
    int second = 45;
    int third = 30;

    // Step by step: find the larger of the first two, then compare that
    // winner with the third.
    int larger_of_two = max_of(first, second);
    int largest = max_of(larger_of_two, third);
    printf("The largest of %d, %d and %d is %d.\n", first, second, third, largest);

    // The same thing in one line. The inner call runs first, and the value
    // it returns becomes the first argument of the outer call.
    printf("In one line: %d\n", max_of(max_of(first, second), third));

    // It also works when numbers are equal.
    printf("The largest of 7, 7 and 2 is %d.\n", max_of(max_of(7, 7), 2));

    return 0;
}

/**
 * @brief Returns the larger of two integers (either one if they are equal).
 */
int max_of(int a, int b)
{
    if (a > b)
    {
        return a;
    }

    // Reached when b is larger, and also when the two are equal, where
    // returning either one is correct.
    return b;
}

/*
 * A function that only knows about TWO numbers solved a problem about
 * THREE, because one call's result can be another call's argument. The same
 * idea finds the largest of four: `max_of(max_of(a, b), max_of(c, d))`.
 *
 * Compare this with Lesson 5, Exercise 3, where the comparison was written
 * out inside `main`. Here it is written once, has a name, and can be tested
 * on its own.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 2_max_of 2_max_of.c
 *   ./2_max_of
 */
Show the solution to exercise 3
3_definition_order.c 76 lines View on GitHub
/**
 * @file 3_definition_order.c
 * @brief Lesson 7, Exercise 3: what happens, and why
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * 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.
 *
 * THE ANSWER:
 * Above `main`: yes, it compiles and runs, and this file is that version.
 * Below `main` with no prototype: no. The reasons are at the end.
 */

#include <stdio.h>

// No prototype here. The whole DEFINITION comes before `main` instead.
int calculate_damage(int strength, int weapon_power)
{
    int calculated_value = strength + (weapon_power * 2);
    return calculated_value;
}

int main(void)
{
    // By the time the compiler reads this call it has already seen the
    // function above, so it knows the name, the two `int` parameters and
    // the `int` return type.
    int total_damage = calculate_damage(20, 8);

    printf("Total calculated damage is: %d\n", total_damage);

    return 0;
}

/*
 * WHY ORDER MATTERS
 *
 * The compiler reads a file once, from top to bottom. When it reaches a
 * function call it must already know what that function takes and returns.
 * A definition tells it everything a prototype would, so a definition
 * placed above the call is enough.
 *
 * Move `calculate_damage` below `main` and the call comes first. GCC then
 * stops with:
 *
 *   error: implicit declaration of function 'calculate_damage'
 *
 * and Clang with:
 *
 *   error: call to undeclared function 'calculate_damage'; ISO C99 and later
 *   do not support implicit function declarations
 *
 * Both mean: "you called something I have not been told about yet". (Very
 * old compilers only warned, guessed that the function returns `int`, and
 * carried on. A wrong guess made the program misbehave when it ran.)
 *
 * SO WHY WRITE PROTOTYPES AT ALL?
 *
 * - With prototypes at the top, the definitions can go in any order, and
 *   `main` can come first, where a reader expects to start.
 * - Two functions that call each other cannot BOTH be defined first.
 * - In programs made of several files (Lesson 31), prototypes in a header
 *   file are how one file learns about functions defined in another.
 *
 * Strict compilers can even ask for them: with the extra flag
 * `-Wmissing-prototypes`, GCC and Clang warn about this file ("no previous
 * prototype for 'calculate_damage'"). The course's own checks use that
 * flag, which is why every lesson lists its prototypes.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 3_definition_order 3_definition_order.c
 *   ./3_definition_order
 */

Finished this lesson?

Mark it complete to track your progress through the course.

Search the course

Type at least two letters. Press / anywhere to search.

↑ ↓ to choose, Enter to open. On a lesson, j and k go to the next and previous lesson.