Pass by value and pass by reference in c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Pass by value and pass by reference in c++

What is the difference between pass by value and pass by reference in C++, and provide an example demonstrating the implications of each method?

7th Mar 2024, 5:25 AM
ATTIQ UR RAHMAN
ATTIQ UR RAHMAN - avatar
1 Answer
+ 1
In C++, "pass by value" means passing a copy of the actual parameter to the function, while "pass by reference" involves passing a reference (memory address) to the actual parameter. Here's a brief example to illustrate the difference: #include <iostream> // Pass by value function void passByValue(int x) { x = 10; } // Pass by reference function void passByReference(int &y) { y = 10; } int main() { int num1 = 5; int num2 = 5; passByValue(num1); passByReference(num2); std::cout << "After pass by value: " << num1 << std::endl; // Output: 5 std::cout << "After pass by reference: " << num2 << std::endl; // Output: 10 return 0; } In the example, "passByValue" receives a copy of "num1", so changes made inside the function don't affect the original variable. On the other hand, "passByReference" modifies the actual data by using a reference, leading to changes reflected outside the function
7th Mar 2024, 7:40 AM
Knight
Knight - avatar