Pass by Value vs Pass by Reference in C++

 

Pass by Value vs Pass by Reference in C++

Pass by Value and Pass by Reference are core concepts in C++ that determine how data is passed into functions. Understanding them helps write efficient and bug-free code.

What is Pass by Value?

In pass by value, a copy of the variable is passed to the function. Changes inside the function do not affect the original variable.

What is Pass by Reference?

In pass by reference, the function receives a reference (alias) to the original variable. Changes made inside the function do affect the original variable.

Example Code (C++)

#include <iostream>
using namespace std;

void passByValue(int x) {
    x = x + 10;
    cout << "Inside passByValue: " << x << endl;
}

void passByReference(int &y) {
    y = y + 10;
    cout << "Inside passByReference: " << y << endl;
}

int main() {
    int a = 5, b = 5;

    passByValue(a);
    cout << "After passByValue: " << a << endl;

    passByReference(b);
    cout << "After passByReference: " << b << endl;

    return 0;
}
  

Expected Output

Inside passByValue: 15
After passByValue: 5
Inside passByReference: 15
After passByReference: 15
    

Summary

  • Pass by Value: Function receives a copy. Original variable is unchanged.
  • Pass by Reference: Function receives a reference. Original variable is modified.
  • Use references when you want to modify original data.
  • Use values when you want to protect the original data.

This concept is essential for efficient memory use, function design, and clean coding in C++.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences