Previous chapter: Chapter 4: Control Flow: Decisions and Loops in C++

As programs grow larger, placing all instructions inside main() becomes unmanageable. Functions are the primary tool for organizing C++ code into reusable, logical, and manageable blocks.

1. The Value of Functions

Functions provide:

2. Defining and Calling Functions

A function definition consists of a return type, a name, a parameter list, and a body.

// 1. Function Definition
// Return Type: int (returns an integer)
// Name: add
// Parameters: int a, int b (takes two integers)
int add(int a, int b) {
    int sum = a + b;
    return sum; // Returns the result
}

int main() {
    // 2. Function Call
    int result = add(10, 20); // Passes 10 and 20 as arguments
    std::cout << "The sum is: " << result << std::endl;
    return 0;
}

3. Function Prototypes (Declarations)

C++ compiles code sequentially. If you define a function after main(), the compiler won't know about it when it reaches the call inside main(). A function prototype (or declaration) fixes this by providing the function's signature before its actual definition.

// Function Prototype (Declaration) placed before main()
int multiply(int x, int y); 

int main() {
    int product = multiply(5, 4); // The compiler knows this exists
    return 0;
}

// Function Definition placed after main()
int multiply(int x, int y) {
    return x * y;
}

4. Parameters and Arguments

A function that does not return a value should be declared with the void return type.

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

5. Function Overloading

C++ allows you to define multiple functions with the same name, as long as their parameter lists are different. This is called function overloading. The compiler selects the correct function based on the number and type of arguments passed.

// Overload 1: Adds two integers
int add_values(int a, int b) {
    return a + b;
}

// Overload 2: Adds two doubles
double add_values(double a, double b) {
    return a + b;
}

int main() {
    std::cout << add_values(5, 10) << std::endl;    // Calls Overload 1 (int)
    std::cout << add_values(5.5, 10.2) << std::endl; // Calls Overload 2 (double)
    return 0;
}

6. Variable Scope

The scope of a variable determines where in your program it can be accessed.