OneCompiler

"Pass by Value" Made Easy

"Pass by value" in C++ is a method of passing arguments to functions where a copy of the actual value is made. This means that any changes made to the parameter inside the function do not affect the original variable outside the function.

Concrete Intuition:

Think of "pass by value" like sending someone a photocopy of a document instead of the original. When you give them the photocopy, they can write notes on it, but those notes don’t affect the original document you have. When they’re done, their changes are only on the photocopy.

Example in C++:

#include <iostream>
using namespace std;

void modifyValue(int num) {
    num = num + 10; // Modify the number
    cout << "Inside modifyValue: " << num << endl; // Prints modified value
}

int main() {
    int originalValue = 5;
    cout << "Before modifyValue: " << originalValue << endl; // Prints original value
    modifyValue(originalValue); // Passing the value to the function
    cout << "After modifyValue: " << originalValue << endl; // Prints original value again
    return 0;
}

What Happens Here:

  1. Before Calling the Function:

    • originalValue is set to 5.
  2. Function Call:

    • When modifyValue(originalValue); is called, a copy of originalValue (which is 5) is passed to the function modifyValue.
  3. Inside the Function:

    • The num inside modifyValue is a separate copy of originalValue.
    • When we change num to num + 10, it becomes 15, but this change does not affect originalValue outside the function.
  4. After the Function Call:

    • After the function finishes executing, we return to main. The originalValue remains 5, and the output will show it hasn't changed.

Key Points:

  • Changes made to num within modifyValue do not reflect back to originalValue.
  • This is because what was passed is a copy, not the original variable itself.

Summary:

When you pass by value, you're handing over a copy of the data. This is useful when you want to ensure the original data remains unchanged, providing safety and reducing unintended side effects. This should clear any confusion about passing variables to functions in C++.