Creating Functions

Creating Functions in C++: A recipe card says what to put in, what you get out, and the steps in between.

The Analogy: The Recipe Card

A recipe card says what to put in, what you get out, and the steps in between. Once it is written you never have to re-derive it: you just say "make the béchamel" and the details happen.

A function is a recipe card for code. It has a name, a list of ingredients (parameters), a stated product (the return type), and a body. And it earns its keep the same way a recipe does — by being used more than once, and by letting the reader of your main method understand what is happening without reading how.

The second benefit is the one beginners undervalue. A function named isValidEmail documents itself. Fifteen lines of inline character-checking does not.


Syntax or Core Structure

#include <iostream>
#include <string>

// returnType name(parameters) { body }
int square(int n) {
    return n * n;
}

// No return value
void greet(const std::string& name) {
    std::cout << "Hello, " << name << "\n";
    // return; is optional in a void function
}

// No parameters
double pi() { return 3.14159265358979; }

// Several parameters
double rectangleArea(double width, double height) {
    return width * height;
}

// Default arguments -- rightmost only
double power(double base, int exponent = 2) {
    double result{1.0};
    for (int i = 0; i < exponent; ++i) { result *= base; }
    return result;
}

// A declaration (prototype) lets you call before defining
bool isEven(int n);

int main() {
    std::cout << square(7) << "\n";              // 49
    greet("Ada");
    std::cout << rectangleArea(3.0, 4.0) << "\n"; // 12
    std::cout << power(5.0) << "\n";             // 25  -- exponent defaults to 2
    std::cout << power(2.0, 10) << "\n";         // 1024
    std::cout << isEven(4) << "\n";              // 1   -- defined below, declared above
    return 0;
}

// The definition can come after main because of the prototype
bool isEven(int n) { return n % 2 == 0; }

A function must be declared before it is called. The prototype (bool isEven(int n); — signature plus semicolon, no body) is how you satisfy that without worrying about ordering. In real projects prototypes live in header files.


Technical Depth: Declarations, Scope and the Stack

Declaration versus definition

// Declaration: a promise. Parameter names are optional here.
double convert(double celsius);

// Definition: the actual code. There may be only ONE.
double convert(double celsius) {
    return celsius * 9.0 / 5.0 + 32.0;
}

You may declare a function as many times as you like, in as many files as you like, but define it exactly once across the whole program. This is the one-definition rule, and violating it produces a linker error rather than a compiler error — which is why "undefined reference to convert" means "you declared it and never wrote the body", while "multiple definition of convert" means you put the body in a header.

Every call gets its own stack frame

int helper(int x) {
    int local = x * 2;      // born when helper is entered
    return local;
}                           // local destroyed here

int main() {
    int local = 5;          // a DIFFERENT variable that happens to share a name
    std::cout << helper(local);
    // helper's local is not visible here at all
}

Calling a function pushes a frame onto the stack holding its parameters and locals; returning pops it. Locals in different functions are entirely unrelated even with identical names, and a function cannot see its caller's variables — everything it needs must come through parameters. That isolation is exactly what makes functions safe to reason about.

The stack is finite (typically 1–8 MB), which is why runaway recursion gives a stack overflow, and why a huge local array is better placed in a std::vector (heap) than on the stack.

Recursion

long long factorial(int n) {
    if (n <= 1) { return 1; }        // BASE CASE -- without this it never stops
    return n * factorial(n - 1);     // and each call must move toward it
}

int fibonacci(int n) {
    if (n < 2) { return n; }
    return fibonacci(n - 1) + fibonacci(n - 2);   // correct but exponentially slow
}

Every recursive function needs a base case and an argument that provably approaches it. Recursion is elegant for tree-shaped problems (directory walks, parsing, divide and conquer) and usually the wrong tool for simple counting — the fibonacci above recomputes the same values millions of times, where a loop is linear.

inline, constexpr and [[nodiscard]]

inline int doubled(int x) { return x * 2; }          // may be expanded at the call site

constexpr int cube(int x) { return x * x * x; }      // can run at COMPILE time
constexpr int c = cube(3);                            // computed during compilation
int runtimeValue = cube(userInput);                    // also fine at runtime

[[nodiscard]] bool save(const std::string& path);     // warn if the result is ignored
save("data.txt");                                     // WARNING: return value discarded

inline is a hint about expansion, and its real modern purpose is permitting a definition in a header without breaking the one-definition rule. constexpr says the function can be evaluated at compile time when its arguments are constants — free performance for pure computations. [[nodiscard]] is worth adding to anything returning a success flag, because a silently ignored error is the bug it prevents.

Designing a function well

// Poor: does three unrelated things, mutates a global, name says nothing
void process();

// Good: one job each, inputs explicit, outputs returned
std::vector<Record> parseCsv(const std::string& text);
bool isValid(const Record& r);
double totalOf(const std::vector<Record>& records);

Four guidelines that hold up in practice. One job per function — if the name needs an "and", split it. Take what you need as parameters rather than reading globals, so the function is testable in isolation. Return results instead of writing to output parameters where you can. And keep it short: past roughly 30 lines, a function is usually two functions.

Parameter passing, summarised

StyleSignatureUse when
By valuef(int x)small primitives, or you want your own copy
By const referencef(const std::string& s)reading anything non-trivial
By referencef(int& x)the caller must see the change
By pointerf(int* x)the argument may legitimately be absent

Real World Example: Refactoring a Payroll Script

Before — one long main that cannot be tested or reused:

int main() {
    double rate{18.50};
    double hours{46.0};
    double gross{0.0};
    if (hours > 40.0) { gross = 40.0 * rate + (hours - 40.0) * rate * 1.5; }
    else              { gross = hours * rate; }
    double tax{0.0};
    if (gross > 1000.0)     { tax = gross * 0.30; }
    else if (gross > 500.0) { tax = gross * 0.20; }
    else                    { tax = gross * 0.10; }
    std::cout << "Net: " << gross - tax << "\n";
    return 0;
}

After — each rule is a named, testable function:

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>

struct Employee {
    std::string name;
    double hourlyRate{0.0};
    double hoursWorked{0.0};
};

struct Payslip {
    double gross{0.0};
    double tax{0.0};
    double net{0.0};
};

constexpr double StandardWeek{40.0};
constexpr double OvertimeMultiplier{1.5};

// Pure: same inputs always give the same output, nothing outside is touched
double grossPay(double rate, double hours) {
    if (hours <= StandardWeek) { return hours * rate; }
    const double overtime = hours - StandardWeek;
    return StandardWeek * rate + overtime * rate * OvertimeMultiplier;
}

double taxRateFor(double gross) {
    if (gross > 1000.0) { return 0.30; }
    if (gross > 500.0)  { return 0.20; }
    return 0.10;
}

// Composed from the two above -- each piece stays independently testable
Payslip calculate(const Employee& e) {
    Payslip p;
    p.gross = grossPay(e.hourlyRate, e.hoursWorked);
    p.tax   = p.gross * taxRateFor(p.gross);
    p.net   = p.gross - p.tax;
    return p;
}

void printPayslip(const Employee& e, const Payslip& p) {
    std::cout << std::fixed << std::setprecision(2)
              << std::setw(10) << std::left << e.name
              << "  gross " << std::setw(8) << std::right << p.gross
              << "  tax " << std::setw(7) << p.tax
              << "  net " << std::setw(8) << p.net << "\n";
}

int main() {
    const std::vector<Employee> staff{
        {"Ada",   18.50, 46.0},
        {"Alan",  22.00, 38.0},
        {"Grace", 31.25, 52.0},
    };

    double payrollTotal{0.0};
    for (const Employee& e : staff) {
        const Payslip p = calculate(e);
        printPayslip(e, p);
        payrollTotal += p.net;
    }

    std::cout << "\nTotal net payroll: " << payrollTotal << "\n";

    // Because grossPay is pure, checking the overtime rule is one line
    std::cout << "Check 46h at 18.50 = " << grossPay(18.50, 46.0)
              << " (expect 906.50)\n";
    return 0;
}

The second version is longer and far better. grossPay and taxRateFor are pure functions — they read only their parameters and write nothing outside themselves, so they can be verified with a single call, as the last line demonstrates. calculate composes them and returns a struct rather than filling out-parameters. printPayslip does formatting and nothing else, so changing the layout cannot break the arithmetic. The magic numbers became named constexpr values. And main now reads as a summary of the process instead of an implementation of it.


Common Mistakes

  • Forgetting to declare a function before calling it. Add a prototype or move the definition up.
  • "Undefined reference" at link time: you declared it but never wrote the body.
  • Falling off the end of a non-void function. Every path must return; -Wall warns.
  • Putting a function definition in a header without inline, causing a multiple-definition link error.
  • Default arguments on non-rightmost parameters. f(int a = 1, int b) does not compile.
  • Repeating a default argument in both the declaration and the definition. State it once, in the declaration.
  • Returning a reference or pointer to a local. It dangles immediately.
  • A function that does everything. If the name needs "and", split it.
  • Reading globals instead of taking parameters, which makes the function untestable.

Best Practices

  1. One job, one function, and let the name state that job precisely.
  2. Prefer pure functions — inputs in, result out, nothing else touched. They are trivial to test.
  3. const Type& for non-trivial reads, by value for small primitives.
  4. Return a value or a struct rather than filling reference out-parameters.
  5. Name constants with constexpr instead of scattering literals through the body.
  6. Add [[nodiscard]] to functions whose return value must not be ignored.
  7. Keep functions under about 30 lines, and put declarations in headers with definitions in .cpp files.

Practice Exercises

  1. Prime helper: Write bool isPrime(int n) handling 0, 1 and negatives correctly, then use it to print every prime below 100. Stop the inner check at the square root.
  2. Refactor: Take a 40-line main that reads three numbers, validates them, computes statistics and prints a report, and split it into four named functions. Confirm main shrinks to about six lines.
  3. Recursion versus iteration: Implement factorial both recursively and with a loop. Time both for n = 20 across a million calls, and note where the recursive version would overflow the stack.