- 1
Help. i somehow grasp the concept of pass by value.
but never understand the pass by reference concept no matter how hard i tried and thats annoying. would anybody care to give this dummy. a dummy explanation. thank you
5 Respuestas
+ 1
Pass by value - Function creates copy of passed variable.
Pass by reference - Function is operating on original variable.
void func(int &foo)
{
foo += 5;
}
int x = 5;
func(x)
std::cout << x; // outputs: 10
if we didn't use "&" in function parameter the output would still be 5.
0
this analogy is flawed. i want some real example codes explained in every line
- 1
Do you know the story of the home hairdresser who had a crush on a beautiful girl ?
Jimmy was a home hairdresser. Unfortunately, he hadn't any client... Each day, when he was cooking, he looked through the window, and he saw every time the same beautiful girl with wonderful hair...
She needed someone to cut her hair but Jimmy didn't know her adress...
So each afternoon Jimmy cutted_hair(beautiful_girl); on a fake head (a copy of the beautiful girl's head. And each evening when he finished, he was really proud of the result! However, each day when he woke up in the morning and cooked, and watched through the window, he saw the girl, with too long hair...
One day he asked the girl her adress. She told him she lived at 0x3h46tr. And the afternoon, Jimmy went to 0x3h46tr and cutted_hair(& beautiful_girl); when he finished he went back Home.
The next morning, as he was cooking, he saw the girl and this time, her hair was cutted...
When a variable is passed normally, a copy of it is created and used in the function. At the end, the copy could have been modified but not the original variable.
If the variable is passed by reference, the adress of it is passed. EVERY changes on the variable in the function is apply to the variable.
- 1
What a story !
- 1
Of course ! Take a look at this :
https://code.sololearn.com/cpD40BP5Du3K/?ref=app
https://code.sololearn.com/cdbBb6xqi1Ke/?ref=app
If you want more informations don't hesitate ask !
PS : I didn't comment every line, I think you're smart enough to understand the ones that I didn't comment.