Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 171 ยท Functions

Functions

Learn C++ functions - defining and calling them, return types and void, declarations vs definitions, how calls work, [[nodiscard]], and how to design small, clear functions.

A function is a named block of code that does one job. You give it some inputs, it runs, and it can hand back a result. You've used functions from the first lesson: main is one, and std::println, std::sqrt and std::ranges::sort are functions written by the standard library authors. Now you'll write your own.

Functions are how programs stay understandable as they grow. Instead of one 500-line main, you build small pieces with clear names (read_scores, average, print_report), and each piece can be read, tested and fixed on its own. Code that would otherwise be copied and pasted lives in one place, so a bug fix applies everywhere at once. This lesson covers defining and calling functions, return values, the difference between a declaration and a definition, and what actually happens during a call. The following lessons dig into parameters, default arguments, return values and overloading.

Defining and calling a function

A function definition has four parts:

C++
double circle_area(double radius) {    // return type, name, parameter list
    return 3.14159 * radius * radius;  // body
}
  • The return type (double) is the type of the value the function gives back.
  • The name (circle_area) follows the identifier rules from Keywords and Identifiers. Functions usually get verb-like names: they do something.
  • The parameter list in parentheses declares the inputs, each with a type and a name. It can be empty: ().
  • The body in braces is the code that runs on each call.

You call a function by writing its name followed by arguments in parentheses: circle_area(2.0). The arguments initialize the parameters, the body runs, and the call expression is replaced by the returned value, so you can use it anywhere a double fits: in a variable, inside another expression, or as an argument to another call.

C++ Your first functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

print_banner has the return type void, which means "returns nothing". You call it for what it does (printing), not for a value, so double x = print_banner(3); would be a compile error. circle_area uses std::numbers::pi (C++20) rather than a hand-typed constant.

Each function is written once and called several times with different arguments. If you later decide the banner should use - instead of =, there's exactly one line to change.

The return statement

return expression; does two things: it gives the value back to the caller, and it ends the function immediately. Code after a return that is reached never runs. A function can have several return statements, and returning early is often the clearest way to handle special cases first:

C++ Early returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

is_prime stops the loop the moment it finds a divisor; there's no need for a break and a flag (compare break, continue and goto). In a void function, a bare return; exits early.

The returned value is converted to the return type if necessary, using the same rules as initialization: return 7; in a function returning double gives back 7.0.

Don't fall off the end

A function with a non-void return type must return a value on every path. If execution reaches the closing brace without a return, the behavior is undefined, and the caller receives garbage or worse:

C++
int sign(int x) {
    if (x > 0) {
        return 1;
    } else if (x < 0) {
        return -1;
    }
}   // sign(0) falls off the end: undefined behavior

GCC catches this with -Wall: warning: control reaches end of non-void function [-Wreturn-type]. Treat that warning as an error, and add the missing return 0;. The only exception is main, described below.

Declarations vs definitions

C++ compiles a file from top to bottom, and you can only call a function the compiler has already heard of. Calling cube(3) in main when cube is defined below main fails with error: 'cube' was not declared in this scope.

There are two fixes. You can put definitions above their first use, which is why small programs often have main at the bottom. Or you can write a declaration (also called a prototype) first: the function's signature followed by a semicolon, without a body.

C++
int cube(int x);         // declaration: "this function exists"

int cube(int x) {        // definition: the actual code
    return x * x * x;
}
  • A declaration tells the compiler the name, return type and parameter types, which is all it needs to check and compile a call.
  • A definition is a declaration plus the body. A program must contain exactly one definition of each function it calls (the One Definition Rule), but it can declare it as many times as it likes.

Parameter names are optional in a declaration (int cube(int);), but good names document the meaning, so keep them.

C++ main first, details below

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

main comes first and reads like a summary of the program; the details follow. This split is also the foundation of multi-file programs: declarations go into a header file that other files #include, and definitions go into a .cpp file that is compiled once. The linker then connects every call to its single definition, as How C++ Works described. Header Files and Multiple Source Files shows the full setup.

main is special

main is the function the operating system calls to start your program, and it has a few unique rules:

  • It must return int. The value is the program's exit code: 0 means success, anything else signals an error to whatever started the program (a shell script, a build system, our code runner).
  • If main reaches its closing brace without a return, it behaves as if it ended with return 0;. That's why most examples in this course have no return in main. No other function gets this exception.
  • You can't call main yourself, take its address or overload it.
  • It has two standard forms: int main() and int main(int argc, char* argv[]), where the second receives the command-line arguments.

What happens during a call

When you call a function, the program:

  1. Evaluates the arguments.
  2. Creates the parameters and initializes them from the arguments. For ordinary parameters like int x, that makes a copy; the function works on its own copy and can't affect the caller's variable. (Parameters shows how references change this.)
  3. Jumps to the function body, which gets its own fresh set of local variables.
  4. On return, destroys the locals and parameters, hands the result back, and continues in the caller right after the call.

The bookkeeping for each active call (its parameters, locals and where to return to) lives in a stack frame on the call stack. When main calls a, which calls b, three frames are stacked up, and they are removed in reverse order as each function returns:

C++ Watching the call stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The trace shows sum_of_squares waiting while square runs twice, each call with its own x and result. The bump call proves that the parameter is a copy: original is still 5. Because every call gets a fresh frame, a function can even call itself; that's recursion. The stack has a limited size (often 1 to 8 MB), so extremely deep call chains overflow it, which Scope, Lifetime and Storage Duration discusses along with local variable lifetimes.

Calls are cheap. With optimization on, the compiler often inlines small functions, pasting their body into the caller so no call happens at all. Don't avoid functions for speed.

Other ways to write the return type

Two alternative spellings appear in modern code:

C++
auto cube(int x) -> int {        // trailing return type: same as int cube(int x)
    return x * x * x;
}

auto half(double x) {            // deduced return type (C++14): double
    return x / 2;
}

The trailing return type puts the type after the parameters. It's mainly useful in templates and lambdas, where the return type depends on the parameters, and some codebases use it everywhere for consistent alignment. A deduced auto return type lets the compiler work out the type from the return statements (they must all agree). It's convenient for short functions, but for a public function an explicit type documents what callers get, so use it sparingly.

[[nodiscard]]: don't ignore the result

Some results must not be thrown away: a computed value, an error code, a "did it work?" flag. Mark such functions with the attribute [[nodiscard]] and the compiler warns when a call ignores the return value:

C++
[[nodiscard]] int twice(int x) {
    return 2 * x;
}

twice(3);    // warning: ignoring return value of 'int twice(int)', declared with attribute 'nodiscard'

Several standard library functions are [[nodiscard]], such as std::vector::empty(). That catches the classic mistake of writing v.empty(); when you meant v.clear();.

Designing good functions

Writing functions is easy; writing good ones is a skill. A few guidelines take you most of the way:

  • One job per function. If you need "and" to describe it (read_and_validate_and_print), split it.
  • Name it for what it does. average(scores) and is_valid_email(text) read like sentences. Boolean functions often start with is_, has_ or can_.
  • Keep it short. A function that fits on one screen can be understood at a glance. Long functions hide bugs.
  • Keep the parameter count small. Four or five parameters suggest that some belong together in a struct.
  • Prefer returning results over changing global variables. A function whose output depends only on its inputs is easy to test and safe to reuse.

Here is a small program built this way. Each function does one thing, and main reads like the outline of the task:

C++ A program made of small functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Change the numbers in the Input box and run again, or clear it to see the error path (main returns 1). The const std::vector<int>& parameters let the functions read the vector without copying it; the next lesson explains exactly why that matters.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? int add_tax(int price) { price += 10; return price; } then int p = 50; int q = add_tax(p); std::println("{} {}", p, q);

    The parameter price is a copy of p. Changing it inside the function doesn't affect p, and the function returns the new value 60.
  2. 2. You call area(3) inside main, but area is defined further down the file with no declaration above main. What happens?

    The compiler reads top to bottom and needs at least a declaration before the call. Add a prototype above main or move the definition up.
  3. 3. What is the difference between a function declaration and a definition?

    A declaration tells the compiler how to call the function. The definition provides the code, and a program needs exactly one definition of each function it uses.
  4. 4. A function int f(int x) returns a value only when x > 0. What happens when it is called with 0?

    Only main gets an implicit return 0. For any other non-void function, reaching the closing brace is undefined behavior; GCC warns with -Wreturn-type.
  5. 5. Which statement about void functions is true?

    void means no value is returned. return; without a value ends the function early, and calling a void function in an expression that needs a value is a compile error.

Summary

  • A function has a return type, a name, a parameter list and a body; you call it with arguments in parentheses.
  • return hands back a value and ends the function at once; early returns keep special cases simple. void functions return nothing and may use return;.
  • Falling off the end of a non-void function is undefined behavior (heed -Wreturn-type); only main implicitly returns 0.
  • A function must be declared before it is called. A declaration is the signature plus ;, a definition adds the body, and each function has exactly one definition.
  • Each call gets its own stack frame with fresh parameters and locals; ordinary parameters are copies of the arguments.
  • auto f() -> T and deduced auto return types are alternative spellings; [[nodiscard]] warns when a result is ignored.
  • Good functions do one job, have clear names, are short and return results rather than changing globals.

Next: Parameters: by Value, by Reference and by const Reference, where you'll learn to choose how data gets into a function without needless copies.