+ 1

Difference between pass by reference and pass by value?

What is the difference between the two, and an example of both.

26th May 2017, 1:29 AM
Sami
7 odpowiedzi
+ 6
Think of it like a birth certificate. You can either make a copy of it, or give them your original directly, without having the overhead of making a copy of it. When you pass in by reference, you are passing the address in memory where that variable is currently stored. So that also means if you change it within in the function, you will be changing the actual variable. Large data types such as structs and classes should always be passed in by reference. Copying them costs performamce. However regular types such as int, bool, char, etc, should just be passed in by value as it makes little difference unless you want to change that variable directly.
26th May 2017, 2:36 AM
aklex
aklex - avatar
+ 6
A suggestion to you Samira, when someone gives you the right answer, do mark their answer as best
26th May 2017, 4:42 AM
Pixie
Pixie - avatar
26th May 2017, 4:07 AM
Sachin Artani
Sachin Artani - avatar
+ 1
You're talking about passing by value and reference. Someone has given you the answer which is pretty good. I hope you got the idea. I am giving u an example to show how it works. #include<iostream> using namespace std: void check(int i) { i=10; } int main() { int x=0; check(x); cout<<x return 0; } #######%% #include<iostream> using namespace std: void check(int i) { i=10; } int main() { int x=0; check(x); cout<<x return 0; } Now please run this two simple programs and let me know what difference you found. First one is passing by value and the later one is passing by reference. Good luck
26th May 2017, 5:20 AM
Adnan
+ 1
The little modification for the mistake I made in the second program. It should be void check( int &i) instead of void check(int i)
26th May 2017, 5:22 AM
Adnan
0
Thank you!
26th May 2017, 4:08 AM
Sami
0
That cleared up my confusion! Haha.
26th May 2017, 5:23 AM
Sami