+ 2

[C++] Can somebody give me an explanation of pass by reference and pass by value?

Hello! Could somebody explain me the concept of pass by reference and pass by value in a function in C++. I would appreciate if you also explain where it would be appreciated to use each one and a short example. I apologise for annoying you😅, but I didn't understand! Thanks!

14th Jul 2017, 4:09 PM
Fernando Rodriguez
Fernando Rodriguez - avatar
7 Answers
+ 3
When a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller's variable. When a parameter is passed by value, the caller and callee have two independent variables with the same value. If the callee modifies the parameter variable, the effect is not visible to the caller.
14th Jul 2017, 4:19 PM
pali
+ 3
Thanks Pali, but I don't understand yet (maybe I am a bit slow or I didn't read the lesson througly). If you could explain a bit more about the caller and the callee it would be great (and again, sorry for annoying).
14th Jul 2017, 4:31 PM
Fernando Rodriguez
Fernando Rodriguez - avatar
14th Jul 2017, 6:00 PM
Manual
Manual - avatar
+ 3
Imagine you want to create a function to eat a sandwich. Passing by reference means like "eat the sandwich that is on the table". You show where the sandwich is, then go and eat that sandwich. At the end of the function, the sandwich is gone. Passing by value means like "make a copy of the sandwich on the table and eat it". After the copy, you now have two different sandwiches. By the end of the function, you have eaten the copy, but the sandwich in the table is still there, untouched.
14th Jul 2017, 6:28 PM
Denis Felipe
Denis Felipe - avatar
+ 2
now that you understood... Most of the time you will pass arguments by value (ie, make a copy). You pass by reference: 1. when you want something done to the parameter. 2. the data is too big to be copied and is more convenient to just pass a reference to it. In this case you normaly pass it as const. An example: strcpy(char* s1, const char* s2) - is an example for both cases: strcpy needs to modify s1, AND it is more convenient to give the pointer of s2 rather than copy it, so both are given by reference :)
22nd Jul 2017, 5:27 PM
lion
lion - avatar
+ 1
Thanks a lot, @Denis Felipe, @Manual and @Pali, I think I got it.👍
14th Jul 2017, 7:28 PM
Fernando Rodriguez
Fernando Rodriguez - avatar
0
Umm I briefly tried to explain and clarify the use & difference of pass by value, pass by reference via reference & pointers, pass by reference in arrays via reference & pointers, & getting a pointer return type from function. https://code.sololearn.com/cNk82nOx24hw/?ref=app https://code.sololearn.com/c4dvux5CvxAA/?ref=app
9th Sep 2019, 11:28 AM
Nikhil kumar