C++ Foundations

Lesson 4 of 6

Functions

A function packages up a piece of logic so you can reuse it by name, instead of retyping the same code everywhere.

#include <iostream>
#include <string>

int add(int a, int b) {
    return a + b;
}

void greet(const std::string& name) {
    std::cout << "Hello, " << name << "!" << std::endl;
}

int main() {
    std::cout << "add(2, 3) = " << add(2, 3) << std::endl;
    greet("Kodstigen");
    return 0;
}

Key ideas

  • A function's declared return type (int, void, ...) must match what it actually returns, void means "returns nothing".
  • In add(int a, int b), a and b are parameters, placeholders for whatever values get passed in when the function is called (the actual values, like 2 and 3, are called arguments).
  • Passing a parameter as const std::string& passes it by reference instead of copying it, faster for large objects like strings, and const promises the function won't modify it.
  • Functions must generally be declared (or defined) before they're used, that's why add and greet appear above main.

📝 Functions Quiz

Passing score: 70%
  1. 1.What does a function declared with return type `void` return?

  2. 2.Declaring a parameter as `const std::string&` avoids copying the argument by passing it by ____.

  3. 3.A function's return type must match the type of value it actually returns.