Unit 2: Loops, Functions & ScopeLesson #6 / 20

Lesson 6: C++ Functions: Pass-by-Value vs Pass-by-Reference (&)

NSNextSemLast Updated: 5 Aug, 2026

⚙️ Modular Programming with C++ Functions

Functions break complex code into reusable, testable components. C++ gives you complete control over how parameters are passed to functions: Pass-by-Value vs Pass-by-Reference.


⚔️ Pass-by-Value vs Pass-by-Reference

  • 📋 Pass-by-Value (void func(int x)): Makes a complete copy of the variable on the stack. Changes made inside the function do NOT affect the original caller's variable.
  • 🔗 Pass-by-Reference (void func(int &x)): Passes the actual memory reference alias. Modifying x inside the function directly updates the caller's variable in place (zero copying cost!).
  • 🛡️ Pass-by-Const-Reference (void func(const std::string &str)): Avoids expensive object copying while preventing the function from modifying the original argument.

  • 💻 Code Example: Swap Function Demonstrating Reference Passing

    C++ Source Code (main.cpp)
    #include <iostream>
    // Pass-by-Reference allows direct modification of original variables
    void swapValues(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
    }
    int main() {
    int x = 10, y = 99;
    std::cout << "Before Swap: x = " << x << ", y = " << y << std::endl;
    swapValues(x, y);
    std::cout << "After Swap: x = " << x << ", y = " << y << std::endl;
    return 0;
    }
    Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
    Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)

    Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

    (c) Microsoft Corporation. All rights reserved.

    C:\Users\Student\CPP_Project>#include <iostream>

    C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp C:\Users\Student\CPP_Project> main.exe Hello World from C++ on Windows 11 Pro! [Process exited with code 0 in 0.001 seconds]

    🛠️ Execution Output:

    Command Execution Snippet
    Before Swap: x = 10, y = 99
    After Swap: x = 99, y = 10
    Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
    Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)

    Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

    (c) Microsoft Corporation. All rights reserved.

    C:\Users\Student\CPP_Project>Before Swap: x = 10, y = 99

    C:\Users\Student\CPP_Project> Before Swap: x = 10, y = 99 Execution successful! Output verified on Windows 11 Pro x86_64. [Process exited with code 0 in 0.002 seconds]

    > 💡 Developer Joke: Why don't functions like pass-by-value?

    > Because they hate living with copies and prefer direct references! 😂

    Interactive Knowledge Check

    Test your understanding of Lesson #6 concepts

    How do you pass a variable by reference in C++ to allow a function to modify the caller's original variable?