C++ Tutorial · Control Flow and Functions · Lesson 9 of 21

C++ Functions

Declare functions, pass by value or reference, defaults, overloading and lambdas.

Parameters: value, reference, const reference

  • By value f(int x) — the function gets a copy.
  • By reference f(int& x) — the function can modify the caller's variable.
  • By const reference f(const std::string& s) — no copy, no modification. The default for large objects.
Example 1
#include <iostream>
#include <string>

void increment(int& n) { ++n; }               // by reference
int area(int w, int h = -1) { return h < 0 ? w * w : w * h; }  // default argument
double area(double r) { return 3.14159 * r * r; }              // overload
std::string shout(const std::string& s) { return s + "!"; }    // const reference

int main() {
    int x = 5;
    increment(x);
    std::cout << x << '\n';
    std::cout << area(3) << ' ' << area(3, 4) << ' ' << area(1.5) << '\n';
    std::cout << shout("hi") << '\n';
}

Output

6
9 12 7.06858
hi!

Run this on your computer — see “Get Started” for setup.

Lambdas

A lambda is an inline anonymous function. The capture list [...] says which outer variables it uses ([=] by value, [&] by reference):

Example 2
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> nums{5, 2, 8, 1};
    int threshold = 3;
    auto bigger = [threshold](int n) { return n > threshold; };
    std::cout << std::count_if(nums.begin(), nums.end(), bigger) << '\n';
    std::sort(nums.begin(), nums.end(), [](int a, int b) { return a > b; });
    for (int n : nums) std::cout << n << ' ';
    std::cout << '\n';
    int total = 0;
    std::for_each(nums.begin(), nums.end(), [&total](int n) { total += n; });
    std::cout << total << '\n';
}

Output

2
8 5 2 1 
16

Run this on your computer — see “Get Started” for setup.

Test yourself

How should you pass a large std::string you only need to read?

  1. std::string
  2. std::string&
  3. const std::string&
  4. std::string*
Show answer

Answer: const std::string&