+ 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!
7 Respuestas
+ 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.
+ 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).
+ 3
Here are links to tutorials on classes and pointers:
http://www.cplusplus.com/doc/tutorial/classes/
http://www.cplusplus.com/doc/tutorial/pointers/
+ 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.
+ 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 :)
+ 1
Thanks a lot, @Denis Felipe, @Manual and @Pali, I think I got it.👍
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