Passing Parameters by Reference in C++

Passing by reference allows the function to modify the actual variable, not just a copy. This is done by using an ampersand (&) in the parameter declaration.

Example: Pass by Reference

#include <iostream>

void increaseByTen(int &number) {
    number += 10;
}

int main() {
    int value = 20;
    increaseByTen(value);
    std::cout << "Value after increase: " << value << std::endl;
    return 0;
}

Explanation: number is a reference to value, so changes to number affect value directly.

Key Takeaways

  • Passing by reference enables direct modification of variables.
  • Useful for large data types to avoid copying.
  • Changes to reference parameters affect the original variable.