Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Defining and calling a function
    4. Functions that return nothing: void
    5. Declare before you call
    6. Parameters are copies
    7. Default arguments
    8. Overloading: one name, several parameter types
    9. Letting the compiler work out the return type: auto
    10. Don’t ignore the result: [[nodiscard]]
    11. Recursion
    12. Which one should I use?
    13. Under the hood
    14. Common pitfalls
    15. Forgetting to return a value
    16. A call that fits two overloads
    17. Try it yourself

    Module 1 · Basics

    1.5Functions

    A function gives a piece of work a name, so you can run it from anywhere with different inputs. Learn how to define and call one, pass values in, get a result back, and let the compiler catch the mistakes.

    About 25 minutesBeginner

    On this page
    1. Key terms
    2. In 30 seconds
    3. Defining and calling a function
    4. Functions that return nothing: void
    5. Declare before you call
    6. Parameters are copies
    7. Default arguments
    8. Overloading: one name, several parameter types
    9. Letting the compiler work out the return type: auto
    10. Don’t ignore the result: [[nodiscard]]
    11. Recursion
    12. Which one should I use?
    13. Under the hood
    14. Common pitfalls
    15. Forgetting to return a value
    16. A call that fits two overloads
    17. Try it yourself

    Key terms

    function
    A named block of code that takes some inputs, does one job and can hand back a result.
    call
    Running a function by writing its name followed by its arguments in parentheses, like square(4).
    parameter
    A variable listed in a function's definition, like n in int square(int n). It holds the value the caller passed in.
    argument
    The value you pass when you call a function. In square(4), the argument is 4.
    return type
    The type written before a function's name. It says what kind of value the function hands back.
    return
    Ends the function and hands a value back to the caller.
    void
    The return type of a function that hands nothing back.
    declaration
    A line that tells the compiler a function's name, parameters and return type, without its body, so you can call it before its definition.
    definition
    The full function, with its body in braces.
    pass by value
    The function gets its own copy of each argument. Changing the copy doesn't touch the caller's variable.
    stack frame
    The block of memory a call uses for its parameters and local variables. It's created when the call starts and removed when it returns.
    default argument
    A value written next to a parameter (int max_score = 100) that is used when the caller leaves that argument out.
    overloading
    Defining several functions with the same name but different parameter types. The compiler picks one from the arguments.
    ambiguous call
    A call where two overloads fit equally well, so the compiler can't choose and stops with an error.
    auto return type
    Lets the compiler work out the return type from the return statements.
    [[nodiscard]]
    An attribute that makes the compiler warn when a caller ignores the function's return value.
    attribute
    Extra information for the compiler, written in double square brackets like [[nodiscard]].
    recursion
    A function that calls itself, each time on a smaller version of the problem.
    base case
    The input where a recursive function returns without calling itself, so the calls stop.

    Programs repeat work: clamp a pixel value, count the bases in a DNA read, average some scores. Copying the same lines everywhere means fixing every copy when one is wrong. A function gives the work a name. You write it once, call it with different inputs, and the compiler checks that every call passes the right things.

    In 30 seconds

    • int square(int n) { return n * n; } defines a function: return type, name, parameters, body.
    • The compiler reads top to bottom, so a function must be declared before you call it.
    • By default, arguments are passed by value: each parameter is a copy, so the function can’t change the caller’s variables.
    • Default arguments, overloading, auto return types and [[nodiscard]] make functions easier to call and harder to misuse.

    Defining and calling a function

    A function definition has four parts: the return type, the name, the parameters in parentheses and the body in braces. return ends the function and hands a value back. To call it, write its name and the arguments in parentheses; the call is replaced by the returned value.

    #include <print>
    
    int square(int n) {
        return n * n;
    }
    
    double average(double a, double b) {
        return (a + b) / 2;
    }
    
    int main() {
        int area = square(4);
        std::println("{} {}", area, square(3) + 1);
        std::println("{}", average(7.0, 8.0));
    }

    Output

    16 10
    7.5

    main is a function too: the one the program starts in. How a C++ program is built explains its return value.

    Functions that return nothing: void

    Some functions do a job but have no result to hand back, like printing. Their return type is void. A void function ends at its closing brace, or earlier at a bare return;.

    #include <print>
    
    void print_bar(int length) {
        if (length <= 0) {
            return; // nothing to draw
        }
        for (int i = 0; i < length; ++i) {
            std::print("#");
        }
        std::println("");
    }
    
    int main() {
        print_bar(5);
        print_bar(0);
        print_bar(2);
    }

    Output

    #####
    ##

    Declare before you call

    As How a C++ program is built showed, the compiler reads your file from top to bottom. When it reaches a call, it must already know the function’s name, parameters and return type. Calling a function that’s defined further down is an error:

    #include <print>
    
    int main() {
        std::println("{}", square(4));
    }
    
    int square(int n) {
        return n * n;
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:4:24: error: ‘square’ was not declared in this scope
        4 |     std::println("{}", square(4));
          |                        ^~~~~~

    Either move the definition above main, or add a declaration at the top: the first line of the function, ending in ; instead of a body. The definition, with the body, can then go anywhere.

    #include <print>
    
    int square(int n); // declaration: enough to call it
    
    int main() {
        std::println("{}", square(4));
    }
    
    int square(int n) {
        return n * n;
    }

    Output

    16

    Declarations are how larger programs share functions between files: a header file holds the declarations, and one .cpp file holds the definitions.

    Parameters are copies

    By default, C++ passes arguments by value. Each parameter is a new variable, initialized with a copy of the argument. The function can change its copy freely; the caller’s variable stays as it was.

    #include <print>
    
    int clamp_pixel(int value) {
        if (value > 255) {
            value = 255; // changes the copy only
        }
        return value;
    }
    
    int main() {
        int brightness = 300;
        int shown = clamp_pixel(brightness);
        std::println("{} {}", brightness, shown);
    }

    Output

    300 255

    To get a result out, return it, as clamp_pixel does. When a function really should change the caller’s variable, or when copying a big object would be slow, pass it by reference instead; References shows how.

    Key ideaReturn results, don't change arguments

    A function that takes its inputs by value and returns its result is the easiest kind to read and test: a call can’t change anything you didn’t assign yourself.

    Default arguments

    Give a parameter a default value with = and callers can leave that argument out. Defaults must come last in the parameter list, because arguments fill parameters from left to right.

    #include <print>
    
    void print_score(int score, int max_score = 100) {
        std::println("{}/{}", score, max_score);
    }
    
    int main() {
        print_score(42);    // max_score is 100
        print_score(7, 10); // max_score is 10
    }

    Output

    42/100
    7/10

    Overloading: one name, several parameter types

    You can define several functions with the same name, as long as their parameter types differ. This is overloading. At each call, the compiler picks the overload whose parameters match the arguments best.

    #include <print>
    
    int larger(int a, int b) {
        return a > b ? a : b;
    }
    
    double larger(double a, double b) {
        return a > b ? a : b;
    }
    
    int main() {
        std::println("{}", larger(3, 8));
        std::println("{}", larger(2.5, 1.5));
    }

    Output

    8
    2.5

    The compiler chooses by the arguments only, never by what you do with the result. Two functions that differ only in their return type can’t both exist.

    Letting the compiler work out the return type: auto

    Write auto as the return type and the compiler uses the type of the value you return. It’s handy for short functions where the type is obvious from the body.

    #include <print>
    
    auto half(double x) {
        return x / 2; // a double, so half returns double
    }
    
    int main() {
        std::println("{}", half(5));
    }

    Output

    2.5

    Every return in an auto function must produce the same type. Returning an int in one place and a double in another is a compile error:

    auto ratio(int hits, int total) {
        if (total == 0) {
            return 0;
        }
        return static_cast<double>(hits) / total;
    }
    
    int main() {
        return static_cast<int>(ratio(1, 2));
    }

    The compiler rejects this

    main.cpp: In function ‘auto ratio(int, int)’:
    main.cpp:5:38: error: inconsistent deduction for auto return type: ‘int’ and then ‘double’
        5 |     return static_cast<double>(hits) / total;
          |            ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~

    Write return 0.0; so both are double, or write the return type yourself: double ratio(int hits, int total).

    Don’t ignore the result: [[nodiscard]]

    Since clamp_pixel doesn’t change its argument, calling it and ignoring the result does nothing. Mark such functions [[nodiscard]], an attribute that tells the compiler the result matters. Ignoring it becomes a warning, and with warnings as errors, it doesn’t compile:

    #include <print>
    
    [[nodiscard]] int clamp_pixel(int value) {
        return value > 255 ? 255 : value;
    }
    
    int main() {
        int pixel = 300;
        clamp_pixel(pixel); // the clamped value is thrown away
        std::println("{}", pixel);
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:9:16: error: ignoring return value of ‘int clamp_pixel(int)’, declared with attribute ‘nodiscard’ [-Werror=unused-result]
        9 |     clamp_pixel(pixel); // the clamped value is thrown away
          |     ~~~~~~~~~~~^~~~~~~
    main.cpp:3:19: note: declared here
        3 | [[nodiscard]] int clamp_pixel(int value) {
          |                   ^~~~~~~~~~~
    cc1plus: all warnings being treated as errors

    The fix is to use the result: pixel = clamp_pixel(pixel);.

    This example is built with -Wunused-result. The site’s examples add -Wno-unused to quiet warnings about unused variables, and in Clang that also turns off this warning. With the flags from Setting up, both compilers report it.

    Recursion

    A function can call itself. This is recursion: the function solves a small part of the problem and calls itself for the rest. Every recursive function needs a base case, an input where it returns without calling itself, or the calls never stop.

    #include <print>
    
    long long factorial(int n) {
        if (n <= 1) {
            return 1; // base case
        }
        return n * factorial(n - 1);
    }
    
    int main() {
        std::println("{}", factorial(5));
        std::println("{}", factorial(20));
    }

    Output

    120
    2432902008176640000

    factorial(5) calls factorial(4), which calls factorial(3), down to factorial(1), which returns 1. Then each call multiplies and returns, back up the chain. Each of those calls is waiting at the same time, and each takes some memory, which Under the hood shows.

    Which one should I use?

    WhatWhenWhyHow
    Written return typeMost functions, and any function you declare before defining it.The reader sees what comes back without reading the body.int square(int n)
    auto return typeShort functions where the type is obvious from the return.Less to write, and the type follows the body if you change it.auto half(double x)
    Default argumentOne parameter almost always has the same value.Callers write less, and there’s still one function to maintain.void print_score(int score, int max_score = 100)
    OverloadsThe same job on different types of input.One name for one idea; the compiler picks the right version.int larger(int, int) and double larger(double, double)
    [[nodiscard]]The returned value is the whole point of the call.The compiler catches a call whose result is thrown away.[[nodiscard]] int clamp_pixel(int value)

    Rule of thumb: write small functions that take their inputs by value and return their result, with a written return type and [[nodiscard]] when ignoring the result would be a bug.

    Under the hood

    Every call gets its own stack frame: a block of memory that holds the call’s parameters and local variables. When main calls clamp_pixel(brightness), a new frame is made for clamp_pixel, and its parameter value is initialized with a copy of brightness. When clamp_pixel returns, its frame is removed, and the returned value lands in shown.

    During clamp_pixel(brightness), just before returnTwo stack frames. The frame for main holds brightness with 300 and shown, which has no value yet. The frame for clamp_pixel holds its own variable value, a copy of brightness that it has changed to 255. The two frames share nothing, so brightness stays 300.Stackmain: framebrightness300shownnot set yetclamp_pixel: framevalue255
    During clamp_pixel(brightness), just before return. Two stack frames. The frame for main holds brightness with 300 and shown, which has no value yet. The frame for clamp_pixel holds its own variable value, a copy of brightness that it has changed to 255. The two frames share nothing, so brightness stays 300.

    The two frames share nothing, which is why changing value can’t touch brightness. A frame also holds the place in the caller to go back to, so the program knows where to continue after return.

    Copying an int or a double costs nothing worth measuring. Copying a big object, like a long DNA sequence in a std::string, means copying all of its characters; that’s what references avoid.

    Recursion makes many frames at once: factorial(20) has 20 frames on the stack at its deepest point. The stack has a fixed, fairly small size, so a recursion millions of levels deep runs out of it. Stack, heap and lifetime shows what a stack overflow looks like.

    PerformanceSmall functions are free

    With optimization on (-O2), the compiler often copies a small function’s body into the caller, so no frame is made at all. Split code into small, well-named functions without worrying about the cost of the call.

    Common pitfalls

    Forgetting to return a value

    If a function has a return type, every path through it must end in return. Falling off the end of a non-void function is undefined behavior: the caller might get garbage, or the program might crash. GCC and Clang warn about it; with warnings as errors, it doesn’t compile:

    #include <print>
    
    char grade(int score) {
        if (score >= 90) {
            return 'A';
        }
        if (score >= 50) {
            return 'B';
        }
    }
    
    int main() {
        std::println("{}", grade(95));
    }

    The compiler rejects this

    main.cpp: In function ‘char grade(int)’:
    main.cpp:10:1: error: control reaches end of non-void function [-Werror=return-type]
       10 | }
          | ^
    cc1plus: all warnings being treated as errors

    The compiler doesn’t know scores are never below 50. Add a final return 'C'; so every path returns.

    A call that fits two overloads

    With int larger(int, int) and double larger(double, double), the call larger(3, 2.5) matches neither exactly. The int version fits the first argument and needs a conversion for the second; the double version is the other way round. Neither is better, so the compiler refuses to guess:

    #include <print>
    
    int larger(int a, int b) {
        return a > b ? a : b;
    }
    
    double larger(double a, double b) {
        return a > b ? a : b;
    }
    
    int main() {
        std::println("{}", larger(3, 2.5));
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:12:30: error: call of overloaded ‘larger(int, double)’ is ambiguous
       12 |     std::println("{}", larger(3, 2.5));
          |                        ~~~~~~^~~~~~~~
    main.cpp:12:30: note: there are 2 candidates
    main.cpp:3:5: note: candidate 1: ‘int larger(int, int)’
        3 | int larger(int a, int b) {
          |     ^~~~~~
    main.cpp:7:8: note: candidate 2: ‘double larger(double, double)’
        7 | double larger(double a, double b) {
          |        ^~~~~~

    Make the types match: larger(3.0, 2.5).

    Common pitfallA recursion with no base case

    A function that always calls itself never stops. GCC and Clang spot the simplest cases and stop with an error; when they can’t tell, the program runs until the stack is full and crashes. Write the base case first.

    Try it yourself

    Try it yourself

    Write two functions. count_base takes a DNA sequence (a std::string) and a base (a char) and returns how many times the base appears. gc_percent uses count_base to return the percentage of G and C bases as a double. The program should print 3 and 50.

    #include <print>
    #include <string>
    
    // Write count_base and gc_percent here.
    
    int main() {
        std::string dna = "GATTACAGCC";
        // Print count_base(dna, 'A') and gc_percent(dna).
    }

    Expected output

    3
    50
    Show a hint

    Count with a loop over the string: for (char base : dna). Then divide using double so the result isn't rounded down: 100.0 * count / total.

    Show a solution
    #include <print>
    #include <string>
    
    [[nodiscard]] int count_base(std::string dna, char base) {
        int count = 0;
        for (char c : dna) {
            if (c == base) {
                ++count;
            }
        }
        return count;
    }
    
    [[nodiscard]] double gc_percent(std::string dna) {
        int gc = count_base(dna, 'G') + count_base(dna, 'C');
        return 100.0 * gc / static_cast<double>(dna.size());
    }
    
    int main() {
        std::string dna = "GATTACAGCC";
        std::println("{}", count_base(dna, 'A'));
        std::println("{}", gc_percent(dna));
    }

    count_base takes the sequence and the base by value and returns a count, so it can't change dna. gc_percent calls it twice and converts to a percentage with 100.0, a double, so the division keeps its fraction. Both are [[nodiscard]]: a call that ignores the count would be a bug.