"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:
-
Before Calling the Function:
originalValueis set to5.
-
Function Call:
- When
modifyValue(originalValue);is called, a copy oforiginalValue(which is5) is passed to the functionmodifyValue.
- When
-
Inside the Function:
- The
numinsidemodifyValueis a separate copy oforiginalValue. - When we change
numtonum + 10, it becomes15, but this change does not affectoriginalValueoutside the function.
- The
-
After the Function Call:
- After the function finishes executing, we return to
main. TheoriginalValueremains5, and the output will show it hasn't changed.
- After the function finishes executing, we return to
Key Points:
- Changes made to
numwithinmodifyValuedo not reflect back tooriginalValue. - 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++.