Tutorials / C++: From Basics to Modern C++ / Functions: parameters, return values and overloading

Functions: parameters, return values and overloading

14 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. Final project: a command-line expense tracker

Why functions exist

A function is a named piece of code you can call from many places. Good functions are small, do one thing, and have a name that says what that thing is. If you cannot name a function without using "and", it probably does two jobs.

#include <iostream>

int square(int x) {
    return x * x;
}

int main() {
    std::cout << square(7) << "\n";   // 49
    return 0;
}

The pieces: the return type (int), the name (square), the parameter list (int x), and the body. A function that returns nothing uses void.

Declaration versus definition

C++ reads your file from top to bottom. A function must be declared before it is used. A declaration (also called a prototype) gives the signature without the body.

#include <iostream>

double average(double a, double b);   // declaration

int main() {
    std::cout << average(3.0, 4.0) << "\n";
    return 0;
}

double average(double a, double b) {  // definition
    return (a + b) / 2.0;
}

This split becomes essential in larger projects. The declaration goes in a header file (.h or .hpp) and the definition goes in a source file (.cpp). Any file that wants to call the function includes the header. Each .cpp file compiles separately, then the linker joins them. Here is the idea:

// mathutil.h
#pragma once
double average(double a, double b);

// mathutil.cpp
#include "mathutil.h"
double average(double a, double b) { return (a + b) / 2.0; }

// main.cpp
#include <iostream>
#include "mathutil.h"
int main() { std::cout << average(1, 2) << "\n"; }

#pragma once stops the header being included twice in the same file. Use angle brackets for standard headers and quotes for your own. To build this by hand: g++ -std=c++20 main.cpp mathutil.cpp -o app.

Pass by value

By default, arguments are copied into the parameters. Changing the parameter inside the function does not change the caller's variable.

void addOne(int n) {
    n = n + 1;      // changes the local copy only
}

int main() {
    int a{5};
    addOne(a);
    std::cout << a << "\n";   // still 5
}

This is safe and simple for small types. For big objects such as long strings or vectors, copying costs time, and the next lesson shows how references avoid it. For now, accept that a copy is made.

Default arguments

You can give trailing parameters a default value, so callers may leave them out.

#include <string>

std::string greet(const std::string& name, const std::string& greeting = "Hello") {
    return greeting + ", " + name + "!";
}

// greet("Asha")            -> "Hello, Asha!"
// greet("Asha", "Salaam")  -> "Salaam, Asha!"

Defaults go only on the right-hand side of the list. Put them in the declaration (the header), not again in the definition.

Overloading

You may have several functions with the same name if their parameter lists differ. The compiler picks the best match from the arguments.

#include <iostream>
#include <string>

void print(int x)                { std::cout << "int: " << x << "\n"; }
void print(double x)             { std::cout << "double: " << x << "\n"; }
void print(const std::string& s) { std::cout << "string: " << s << "\n"; }

int main() {
    print(5);
    print(2.5);
    print(std::string{"hi"});
}

The return type alone cannot distinguish overloads. Be careful when overloads are too similar, for example print(long) and print(int); a call with a short or a character may surprise you.

Returning several values

A function returns one thing, but that thing can be a small struct, a std::pair, or a std::tuple. Structured bindings, added in C++17, unpack it neatly.

#include <utility>
#include <iostream>

std::pair<int, int> divide(int a, int b) {
    return {a / b, a % b};
}

int main() {
    auto [quotient, remainder] = divide(17, 5);
    std::cout << quotient << " r " << remainder << "\n";   // 3 r 2
}

inline, constexpr and auto return

A constexpr function can run at compile time when given constant arguments, and at run time otherwise. It must be simple enough for the compiler to evaluate.

constexpr int factorial(int n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
}

static_assert(factorial(5) == 120);   // checked while compiling
int table[factorial(4)];              // size 24, fixed at compile time

A function defined in a header must be marked inline, or the linker will complain about duplicate definitions once two .cpp files include it. (constexpr functions are implicitly inline.) The word inline today is about this linking rule, not about speed. The compiler decides what to expand on its own.

You can write auto as the return type and let the compiler deduce it, but I only do that for short helper functions. For public functions I prefer to write the return type, because it is documentation.

The common mistake

Forgetting to return a value from a non-void function on some path. The compiler may only warn, and the result at run time is undefined behaviour. Another frequent one is putting a function definition in a header without inline, which compiles fine in a one-file test and then breaks the moment a second file includes it.

Try it yourself

  1. Write bool isPrime(int n) and a main that prints all primes below 50.
  2. Move isPrime into prime.h and prime.cpp and compile the two files together.
  3. Write overloaded maxOf functions for two ints and for three ints. Call both.
cpp
#include <iostream>

int square(int x) {
    return x * x;
}

int main() {
    std::cout << square(7) << "\n";   // 49
    return 0;
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account