Lesson 11 — Fundamentals

Functions

Functions package a block of logic under a name so it can be reused, tested, and reasoned about independently of the rest of your program.

Declaring and Calling Functions

A function has a return type, a name, a parameter list, and a body. If a function does not return a value, its return type is void.

C++ — Function basics
double calculateArea(double width, double height) {
    return width * height;
}

void printReceipt(std::string item, double price) {
    std::cout << item << ": R" << price << std::endl;
}

int main() {
    double area = calculateArea(4.0, 3.5);
    printReceipt("Notebook", 45.99);
    return 0;
}

Pass by Value vs Pass by Reference

By default, arguments are passed by value — the function receives a copy, so changes inside it do not affect the caller's variable. Passing by reference (using &) lets a function modify the original variable directly, and also avoids copying large objects.

C++ — Pass by reference
void doubleValue(int &n) {
    n = n * 2;
}

int main() {
    int x = 10;
    doubleValue(x);
    std::cout << x << std::endl; // 20 — the original was modified
    return 0;
}

Function Overloading

C++ allows multiple functions with the same name as long as their parameter lists differ. The compiler chooses the correct version based on the arguments you pass.

Common Mistakes

  • Forgetting to declare a function's return type, or returning a value from a void function.
  • Expecting a pass-by-value parameter to change the caller's variable — it won't, only pass-by-reference does.
  • Writing overloaded functions that differ only in return type, which C++ does not allow (parameters must differ).
  • Calling a function before it is declared, without a forward declaration or prototype at the top of the file.

Professional Tip

Pass large objects like std::string or std::vector by const reference (const std::string&) when you don't need to modify them. This avoids an expensive copy while still preventing accidental changes.

Your Turn

Write a function isPrime(int n) that returns a bool indicating whether n is a prime number, then call it in a loop to print all prime numbers between 1 and 50.

Mini Quiz

What is the key difference between pass-by-value and pass-by-reference?