Lesson 06-C++ Functions

Function Basics

  • Function Definition: Includes the return type, function name, and a list of zero or more parameters along with the function body.
  • Call Operator: The call operator is a pair of parentheses (), applied to an expression that is either a function or a pointer to a function.
  • Inside the parentheses is a comma-separated list of arguments.
  • Function Call Process:
      1. The execution of the calling function is interrupted.
      1. The called function begins execution.
  • Parameters and Arguments: The number and types of parameters and arguments must match.
  • Return Type: void indicates the function returns no value. The return type of a function cannot be an array type or function type, but it can be a pointer to an array or function.
  • Name: The name is part of the program text and is visible within its scope.

Local Objects

  • Lifetime: The lifetime of an object is the period during program execution when the object exists.
  • Local Variable: Parameters and variables defined inside the function body are collectively called local variables. They are local to the function and hidden from outside the function.
  • Automatic Object: An object that exists only during the execution of a block. When the block finishes execution, its value becomes undefined.
  • Local Static Object: A local variable of type static, whose lifetime persists across function calls.

Function Declaration and Definition

  • Function Declaration: The only difference between a function declaration and definition is that a declaration does not require a function body and is replaced with a semicolon. Function declarations mainly describe the function’s interface, also known as the function prototype.
  • Declare functions in header files: It is recommended to declare variables in header files and define them in source files.
  • Separate Compilation: CC a.cc b.cc compiles directly into an executable; CC -c a.cc b.cc compiles into object code a.o b.o; CC a.o b.o links into an executable.
  • A function definition includes the actual implementation, i.e., the code in the function body.
  • A function declaration (also called a function prototype) tells the compiler the function’s name, return type, and parameter list. It does not include the function body.
// Function definition
int add(int a, int b) {
    return a + b;
}

// Function declaration in another file or earlier
int add(int, int);

Function Prototype

A function prototype must be provided before the function is called. It informs the compiler how to invoke the function. Prototypes are typically declared in header files.

// Declaration
int add(int, int);

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

Parameter Passing

  • Pass-by-Value: A copy of the argument is passed; the original data is not affected.
  • Pass-by-Reference: A reference to the argument is passed; any modification affects the original data.
  • Pass-by-Pointer: Similar to pass-by-reference, but requires explicit dereferencing.
void modifyByValue(int val) {
    val = 10; // Does not affect original data
}

void modifyByReference(int& ref) {
    ref = 10; // Modifies original data
}

void modifyByPointer(int* ptr) {
    *ptr = 10; // Also modifies original data
}

Calling a Function

To call a function, use the function name followed by parentheses, providing the necessary arguments inside.

int result = add(5, 3); // Call the add function

Return Value

A function can return a value specified via the return statement.

int add(int a, int b) {
    return a + b; // Returns the sum of two numbers
}

Function Overloading

Function overloading allows multiple functions with the same name in the same scope, as long as their parameter lists differ.

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

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

Inline Functions

An inline function is a special function intended to reduce the overhead of function calls. Declared using the inline keyword.

inline int square(int x) {
    return x * x;
}

Default Parameters

Default values can be provided for parameters in function declarations or definitions. If the corresponding argument is omitted during a call, the default value is used.

void printMessage(const std::string& message = "Hello") {
    std::cout << message << std::endl;
}

Linkage Specifiers

Linkage specifiers control the linkage properties of functions. For example, extern "C" tells the C++ compiler to link the function using C linkage.

extern "C" void cFunction();

Advanced Function Features

Variadic Parameter Lists

In C++, variadic arguments can be implemented using C-style macros or the <cstdarg> library introduced in C++11. <cstdarg> provides the va_list type to handle a variable number of arguments.

#include <iostream>
#include <cstdarg>

void printVarArgs(const char* prefix, ...) {
    va_list args;
    va_start(args, prefix);
    while (char arg = va_arg(args, char)) {
        std::cout << arg;
    }
    va_end(args);
    std::cout << std::endl;
}

int main() {
    printVarArgs("Hello", 'W', 'o', 'r', 'l', 'd', '\0');
    return 0;
}

Recursive Functions

A recursive function calls itself within its definition or implementation. Recursive functions typically require a clear termination condition to prevent infinite recursion.

#include <iostream>

int factorial(int n) {
    if (n <= 1)
        return 1;
    else
        return n * factorial(n - 1);
}

int main() {
    std::cout << "Factorial of 5 is: " << factorial(5) << std::endl;
    return 0;
}

Function Pointers

A function pointer is a pointer to a function. It can be passed as an argument to other functions or stored in data structures.

#include <iostream>

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

int subtract(int a, int b) {
    return a - b;
}

int operate(int a, int b, int (*operation)(int, int)) {
    return operation(a, b);
}

int main() {
    int result = operate(10, 5, add);
    std::cout << "Result of addition: " << result << std::endl;

    result = operate(10, 5, subtract);
    std::cout << "Result of subtraction: " << result << std::endl;

    return 0;
}

Parameter Type Conversion

In C++, type conversion can be explicit or implicit through type deduction in function parameters.

#include <iostream>

void printDouble(double d) {
    std::cout << "Double value: " << d << std::endl;
}

int main() {
    int i = 10;
    printDouble(i); // Automatically converted to double

    return 0;
}

Lambda Expressions

Lambda expressions, supported since C++11, are anonymous functions that simplify code and improve readability. They can capture surrounding variables and be defined anywhere.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    // Use lambda expression for sorting
    std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
        return a > b; // Descending order
    });

    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Function Templates

Function Templates

Function templates allow writing generic functions that accept parameters of different types. The basic syntax is:

template<typename T>
return_type function_name(parameters) {
    // function body
}

The typename keyword can be replaced with class; both are equivalent in template contexts. T is a template parameter representing a type.

template<typename T>
T max(T a, T b) {
    return a > b ? a : b;
}

int main() {
    int x = 10, y = 20;
    double z = 10.5, w = 20.5;

    std::cout << "Max of " << x << " and " << y << " is " << max(x, y) << std::endl;
    std::cout << "Max of " << z << " and " << w << " is " << max(z, w) << std::endl;

    return 0;
}

Template Specialization

Template specialization allows providing different implementations for specific types. It includes full specialization and partial specialization.

  • Full Specialization: Provides concrete types for all template parameters.
  • Partial Specialization: Provides concrete types for some template parameters.
template<typename T>
T max(T a, T b) {
    return a > b ? a : b;
}

// Full specialization
template<>
const char* max<const char*>(const char* a, const char* b) {
    return strcmp(a, b) > 0 ? a : b;
}

// Partial specialization
template<typename T>
std::string max(std::string a, T b) {
    return a;
}

int main() {
    int x = 10, y = 20;
    double z = 10.5, w = 20.5;
    const char* str1 = "Hello";
    const char* str2 = "World";

    std::cout << "Max of " << x << " and " << y << " is " << max(x, y) << std::endl;
    std::cout << "Max of " << z << " and " << w << " is " << max(z, w) << std::endl;
    std::cout << "Max of " << str1 << " and " << str2 << " is " << max(str1, str2) << std::endl;

    return 0;
}

Template Metaprogramming

Template metaprogramming is a technique that uses templates to perform computations at compile time. It enables creating complex types and values at compile time to optimize runtime performance.

template<int A, int B>
struct Add {
    static const int value = A + B;
};

int main() {
    std::cout << "Addition of 10 and 20 is " << Add<10, 20>::value << std::endl;
    return 0;
}

More Template Metaprogramming Examples

Below is a more complex template metaprogramming example demonstrating factorial computation using templates.

template<int N>
struct Factorial {
    static const int value = N * Factorial<N - 1>::value;
};

template<>
struct Factorial<0> {
    static const int value = 1;
};

int main() {
    std::cout << "Factorial of 5 is " << Factorial<5>::value << std::endl;
    return 0;
}

Function Objects and Functors

Function Objects

Function objects (also known as functors or callable objects) are a design pattern in C++ that allow class instances to be called like regular functions. They typically contain state (member variables) and overload the operator().

#include <iostream>

// Function object class
class MyFunc {
public:
    int operator()(int a, int b) const {
        return a + b;
    }
};

int main() {
    MyFunc func;
    int result = func(5, 3); // Call function object
    std::cout << "Result: " << result << std::endl;
    return 0;
}

Functors

A functor is a class or struct that implements operator(), allowing it to be called like a function. Functors are commonly used where behavior needs to be passed, such as in comparison operations for algorithms.

#include <iostream>
#include <algorithm>
#include <vector>

// Functor class
struct GreaterThan {
    bool operator()(int a, int b) const {
        return a > b;
    }
};

int main() {
    std::vector<int> numbers = {5, 2, 9, 1, 5, 6};
    std::sort(numbers.begin(), numbers.end(), GreaterThan());
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    return 0;
}

More Examples

Here is a more specific example showing how to use function objects and functors to implement custom sorting logic.

#include <iostream>
#include <algorithm>
#include <vector>

// Functor class
struct CustomComparator {
    bool operator()(const std::string& a, const std::string& b) const {
        return a.size() < b.size(); // Sort by string length
    }
};

int main() {
    std::vector<std::string> words = {"apple", "banana", "cherry", "date"};
    std::sort(words.begin(), words.end(), CustomComparator());

    for (const auto& word : words) {
        std::cout << word << " ";
    }
    std::cout << std::endl;

    return 0;
}

Summary

  • Function Objects: Class instances that implement operator() and can be called like regular functions.
  • Functors: Classes or structs that implement operator(), typically used to pass behavior, such as in sorting algorithms.

C++ Version-Specific Function Features

C++11 New Features

nullptr as Function Pointer In C++11, nullptr is a new keyword representing a null pointer constant. It can be assigned to any pointer type, including function pointers.

noexcept Specifier The noexcept specifier declares that a function does not throw exceptions or that an expression does not throw under certain conditions.

void myFunction() noexcept {}

int main() {
    int* p = nullptr; // nullptr as pointer
    void (*fp)() = nullptr; // nullptr as function pointer

    myFunction(); // noexcept specifier
    return 0;
}

C++14 New Features

Generic Lambda Expressions C++14 introduced generic lambda expressions, allowing lambdas to capture variables of any type.

Variable Templates Variable templates allow declaring variables that depend on template parameters.

auto lambda = []<typename T>(T x, T y) {
    return x + y;
};

template<typename T>
constexpr T pi = 3.14159265358979323846T;

int main() {
    auto result = lambda(10, 20); // Generic lambda
    std::cout << "pi<double>: " << pi<double> << std::endl; // Variable template
    return 0;
}

C++17 New Features

Structured Bindings

Structured bindings allow destructuring values directly from containers or tuples.

  • std::optional and std::variant as Function Return Types
  • std::optional and std::variant are new types in the C++17 standard library, used as function return types to represent possibly absent results or multiple result types.
#include <optional>
#include <variant>
#include <tuple>
#include <iostream>

std::optional<int> getOptional() {
    return 42;
}

std::variant<int, std::string> getVariant() {
    return "Hello";
}

int main() {
    auto [x, y] = std::make_tuple(10, 20); // Structured binding
    std::cout << "x: " << x << ", y: " << y << std::endl;

    auto opt = getOptional();
    if (opt) {
        std::cout << "Optional value: " << *opt << std::endl;
    }

    auto var = getVariant();
    if (std::holds_alternative<int>(var)) {
        std::cout << "Variant as int: " << std::get<int>(var) << std::endl;
    } else if (std::holds_alternative<std::string>(var)) {
        std::cout << "Variant as string: " << std::get<std::string>(var) << std::endl;
    }

    return 0;
}

C++20 New Features

Template Parameter Deduction C++20 allows using auto and consteval in template functions for parameter deduction.

Concept Constraints Concept constraints allow defining requirements that template parameters must satisfy.

std::ranges and Functional Programming Style C++20 introduced the std::ranges library, supporting more efficient range processing and functional programming style.

#include <ranges>
#include <iostream>
#include <vector>

template<typename T>
concept Numeric = std::is_arithmetic_v<T>;

template<Numeric T>
auto sum(const std::vector<T>& v) {
    return std::ranges::accumulate(v, T{0});
}

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    auto total = sum(numbers);
    std::cout << "Sum: " << total << std::endl;

    return 0;
}

Exception Handling

Basic Syntax of Exception Handling

C++ exception handling primarily involves the following keywords:

  • try: Marks a block of code where exceptions might occur.
  • catch: Catches and handles exceptions.
  • throw: Throws an exception.
  • finally: C++ has no direct finally keyword, but std::at_exit or RAII (Resource Acquisition Is Initialization) can achieve similar effects.

Example

Here is a simple exception handling example:

#include <iostream>
#include <stdexcept>

int divide(int a, int b) {
    if (b == 0) {
        throw std::runtime_error("Division by zero");
    }
    return a / b;
}

int main() {
    try {
        int result = divide(10, 0);
        std::cout << "Result: " << result << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Caught exception: " << e.what() << std::endl;
    } catch (...) {
        std::cerr << "Caught unknown exception" << std::endl;
    }
    return 0;
}

Key Concepts in Exception Handling

  • Throwing Exceptions: When an error occurs, an exception object is typically thrown using the throw statement.
  • Catching Exceptions: catch blocks catch and handle exceptions. You can specify catching specific exception types.
  • Exception Safety: Ensures the program remains in a consistent state after an exception, usually achieved via RAII for resource management.
  • Exception Propagation: If a catch block does not handle an exception, it can be rethrown to propagate upward.
  • Exception Specification: Use the noexcept keyword to specify whether a function may throw exceptions.

Example

#include <iostream>
#include <stdexcept>
#include <cassert>

void check(int value) {
    if (value < 0) {
        throw std::invalid_argument("Value cannot be negative");
    }
}

int safe_divide(int a, int b) noexcept {
    assert(b != 0); // Static assertion, checked at compile time
    return a / b;
}

int main() {
    try {
        check(-1);
        int result = safe_divide(10, 0);
        std::cout << "Result: " << result << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Caught exception: " << e.what() << std::endl;
    } catch (...) {
        std::cerr << "Caught unknown exception" << std::endl;
    }
    return 0;
}

Share your love