Please give the difference between call by value and call by reference | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Please give the difference between call by value and call by reference

25th Dec 2016, 4:26 AM
ranjith
4 Answers
+ 6
Lets say you have two user-defined functions: void func1 (int x) { x = 1; } void func2 (int& x) { x = 1; } In your code, you do the following: int main() { int i = 0; func1(i); cout << i << endl; // outputs 0 func2(i); cout << i << endl; // outputs 1 return 0; } As you can see from the above code, we say that we pass i by value into func1. Only the value is passed into the function, and not the actual variable itself. In func2, i was passed into the function by reference. We say that we pass the functional address of the variable into the function. Any changes made to the variable passed by reference will be reflected in main.
25th Dec 2016, 5:37 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
Calling by value directly prints out the stored value on the given address in memory, while a reference REFERS to an address in memory and if you were to print out &variable, you'd get the address of that variable. I don't know if you're on that level yet, ignore it if it confuses you, but later on you'll be passing classes to other functions and stuff by reference as well (you'll be giving their address) so it doesn't make a copy of itself (and you don't need the copying constructor). So basically a reference is an address and a value is the information that is stored on that address (if any) and what @Hatsy mentioned is really important as well, I shouldn't repeat what was already written.
25th Dec 2016, 5:47 AM
Faris Hasković
Faris Hasković - avatar
0
just a suggestion: that is pass by value and pass by reference. haven't heard calling by ... before.
25th Dec 2016, 8:41 AM
Kourosh Azizi
Kourosh Azizi - avatar
0
taq u guyzzz
4th Jan 2017, 4:48 PM
ranjith