Pass-by-Value
In pass-by-value, a copy of the actual arguments is passed to the function. Any changes made to the parameters inside the function have no effect on the actual arguments.
Pass-by-Reference
In pass-by-reference, the actual arguments are passed to the function, allowing the function to modify the values of the arguments directly.
Program Implementation
#include <iostream> using namespace std; // Function to swap numbers using pass-by-value void swapByValue(int a, int b) { if (a != b) { int temp = a; a = b; b = temp; cout << "Inside swapByValue (a, b): " << a << " " << b << endl; } } // Function to swap numbers using pass-by-reference void swapByReference(int &a, int &b) { if (a != b) { int temp = a; a = b; b = temp; cout << "Inside swapByReference (a, b): " << a << " " << b << endl; } } int main() { int x = 5, y = 10; // Swap using pass-by-value cout << "Before swapByValue (x, y): " << x << " " << y << endl; swapByValue(x, y); cout << "After swapByValue (x, y): " << x << " " << y << endl; // Swap using pass-by-reference cout << "Before swapByReference (x, y): " << x << " " << y << endl; swapByReference(x, y); cout << "After swapByReference (x, y): " << x << " " << y << endl; return 0; }
Explanation
- swapByValue Function:
- This function takes two integers as parameters by value.
- It checks if the values are different, and if so, it swaps them using a temporary variable.
- Since the function uses pass-by-value, changes made inside the function do not affect the original variables.
- swapByReference Function:
- This function takes two integers as parameters by reference.
- It checks if the values are different, and if so, it swaps them using a temporary variable.
- Since the function uses pass-by-reference, changes made inside the function directly affect the original variables.
Output
Before swapByValue (x, y): 5 10 Inside swapByValue (a, b): 10 5 After swapByValue (x, y): 5 10 Before swapByReference (x, y): 5 10 Inside swapByReference (a, b): 10 5 After swapByReference (x, y): 10 5
Key Points
- Pass-by-Value: The original values of
x
andy
remain unchanged after the function call. - Pass-by-Reference: The original values of
x
andy
are swapped after the function call