Functions#

Based on C++ Primer, 5th ed. Chapter 6 (Functions).

A function is a block of code with a name. Functions can be overloaded, meaning that the same name may refer to several different functions.

1. Object Lifetime and Function Declarations#

Automatic Objects#

An automatic object is an object that exists only while a block is executing.

  • Parameters are automatic objects. They are created (initialized) when the function is called and destroyed when the block is exited.

Local static Objects#

Each local static object is initialized before the first time execution passes through the object’s definition.

  • Local statics are not destroyed when a function ends; they are destroyed when the program terminates.
size_t CountCalls() {
    static size_t ctr = 0; // Initialized once before execution first passes through
    return ++ctr;          // Persists across calls until the program terminates
}

int main() {
    for (size_t i = 0; i != 10; ++i) {
        cout << CountCalls() << " "; // Prints numbers 1 through 10
    }
    return 0;
}

Header Declarations#

Functions should be declared in header files and defined in source files.

  • When validating a function call, the compiler inspects only the declaration in the header file, allowing headers to serve as common interfaces across source files.

2. Passing Arguments by Reference#

Passing parameters by reference (T& or const T&) serves two primary purposes:

  1. When we want to change the value of an argument.
  2. When copying is expensive or impossible (e.g., large containers, or non-copyable types like iostream).

Prefer Reference to const#

  • Caveat: Reference parameters that are not changed inside a function should be references to const.
  • Use reference to const when possible:
    • const T& can bind to both lvalues and rvalues.
    • Non-const T& cannot bind to rvalues.
    • Defining a parameter as plain T& when modification is unnecessary prevents callers from passing literals or temporaries, severely restricting the function’s usability.

Modern C++ Exception (Sink Parameters That Must Copy): When a function or constructor needs to keep its own copy of the argument anyway, accept it by value (T) and std::move or swap it into place rather than taking const T& (when an rvalue argument is passed to the parameter, Copy Elision eliminates the copy completely). See Copy Elision & Move Semantics: Two Function Design Rules for Taking Advantage of Copy Elision (RVO).


3. Functions with Varying Parameters#

C++ provides multiple mechanisms for functions that accept varying numbers of arguments:

std::initializer_list (C++11)#

Used when all arguments share the same type but their count is variable.

  • Unlike vector, the elements in an initializer_list are always const values (immutable).
  • It provides .begin() and .end() member functions, allowing traversal via range for loops.
void ErrorMsg(initializer_list<string> il) {
    for (const auto &elem : il) { // Traversal using .begin() and .end()
        cout << elem << " ";
    }
    cout << endl;
}

// Pass arguments enclosed in curly braces
ErrorMsg({"functionX", "expected", "actual"});

Ellipsis Parameter (...)#

Inherited from C for compatibility (e.g., printf).

  • Bypasses compiler type checking, offering no type safety.
  • Should generally be avoided in C++ except when interfacing with C libraries.

4. Returning a Pointer to an Array#

Because we cannot copy an array, a function cannot return an array directly. However, it can return a pointer or reference to an array.

Direct Declaration Syntax Complexity#

Directly declaring a function that returns a pointer to an array can be intimidating:

int (*f(int i))[10];
  • f is a function taking a single int parameter and returning a pointer to int[10] (int (*)[10]).

Four Ways to Simplify the Declaration#

1. typedef Type Alias#

Alias either the array type or the pointer-to-array type:

typedef int arrT[10]; // arrT is an array of ten ints
arrT* f1(int i);      // returns a pointer to an array of ten ints

typedef int (*pointer_to_array)[10];
pointer_to_array f2(int i);

2. using Alias Declaration (C++11)#

Equivalent to typedef but uses cleaner assignment syntax:

using arrT = int[10];
arrT* f1(int i);

using pointer_to_array = int (*)[10];
pointer_to_array f2(int i);

3. Trailing Return Type (C++11)#

Places the return type after the parameter list using auto as the leading placeholder and -> return_type after parameters:

auto f(int i) -> int(*)[10]; // Returns a pointer to an array of ten ints

4. Using decltype#

When the target array object already exists and its type is known:

int odd[] = {1, 3, 5, 7, 9};
int even[] = {0, 2, 4, 6, 8};

// Note: decltype does not decay arrays to pointers; it preserves the array type (int[5]),
// so an explicit * is required to return a pointer.
decltype(odd) *arrPtr(int i) {
    return (i % 2) ? &odd : &even; // Returns a pointer to the array
}