Lesson 10 of 25

Functions

Defining and Calling Functions

Functions encapsulate reusable blocks of code. C++ functions must declare their return type and parameter types.

Example
// Function with return value
int add(int a, int b) {
    return a + b;
}

// Void function
void greet(string name) {
    cout << "Hello, " << name << "!" << endl;
}

// Default parameters
double calculateTax(double amount, double rate = 0.08) {
    return amount * rate;
}

// Function overloading
int max(int a, int b) { return (a > b) ? a : b; }
double max(double a, double b) { return (a > b) ? a : b; }

int main() {
    cout << add(5, 3) << endl;          // 8
    greet("Alice");                      // "Hello, Alice!"
    cout << calculateTax(100) << endl;   // 8.0
    cout << max(10, 20) << endl;         // 20
    cout << max(3.14, 2.71) << endl;     // 3.14
    return 0;
}

Pass by Value vs Reference

C++ supports passing arguments by value (copy) or by reference (direct access to the original).

Example
// Pass by value — copy of the variable
void doubleValue(int x) {
    x *= 2; // only modifies the copy
}

// Pass by reference — modifies original
void doubleRef(int& x) {
    x *= 2; // modifies the original variable
}

// Pass by const reference — efficient, no copy, no modify
void print(const string& text) {
    cout << text << endl;
}

int main() {
    int num = 5;
    doubleValue(num);
    cout << num << endl; // still 5

    doubleRef(num);
    cout << num << endl; // now 10
    return 0;
}