Functions: Value vs Reference

⚡ C++ Lesson 9 Beginner

Functions are modular, reusable code units. In C++, parameters can be passed by value, by pointer, or by reference to optimize performance.

1 Pass-by-Value vs. Pass-by-Reference

Choosing parameter passing patterns controls execution safety and efficiency:

  • Pass-by-Value: Copies the parameter value. The original variable remains unchanged.
  • Pass-by-Reference (`Type&`): Passes a reference to the original variable, allowing the function to modify it directly. Highly recommended for large objects (like vectors or strings) to avoid copy overhead.
  • Const References (`const Type&`): Passes a reference to avoid copying, but marks it `const` to prevent the function from modifying the original value. This provides both safety and high performance.
2 Parameter Passing Code

Let's run a program illustrating parameter passing mechanics:

C++ — Parameter Passing ▶ Run Code
#include <iostream>

// Pass-by-value
void modifyVal(int x) {
    x = 100;
}

// Pass-by-reference
void modifyRef(int &x) {
    x = 100; // Modifies the original variable directly
}

int main() {
    int num = 50;

    modifyVal(num);
    std::cout << "After modifyVal: " << num << "\n"; // Remains 50

    modifyRef(num);
    std::cout << "After modifyRef: " << num << "\n"; // Updated to 100

    return 0;
}
3 Code Challenge
Challenge: Write a utility function called `swap` that accepts two integer reference parameters and swaps their values. Test it inside `main()` with two initialized variables, print them before and after the swap, and confirm they swapped successfully.