Functions, references and lambdas

Pass by value or by reference, default arguments, overloading, templates and lambdas.

Runs in Zerethon IDE · C++ (GCC 14) Official C++ documentation ↗
main.cpp
#include <iostream>
#include <string>

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

void double_it(int& x) { x *= 2; }

template <typename T>
T largest(T a, T b) { return a > b ? a : b; }

int main() {
    std::cout << greet("Ada") << ' ' << greet("Linus", "Hi") << '\n';
    int n = 21;
    double_it(n);
    std::cout << n << ' ' << largest(3, 9) << ' ' << largest(2.5, 1.5) << '\n';

    int offset = 10;
    auto add = [offset](int x) { return x + offset; };
    std::cout << add(5) << '\n';
}

Output

Hello, Ada! Hi, Linus!
42 9 2.5
15
  • Parameters are copies by default. int& x lets the function change the caller's variable; const std::string& avoids copying without allowing changes.
  • A function must be declared before it is called (define it above, or write a declaration).
  • A lambda [captures](params) { body } is a small function value — handy with std::sort and other algorithms.