+ 1

Difference between call by value and call by reference?

15th Sep 2016, 5:03 PM
manan Kanswal
3 Réponses
+ 3
Pass by value is the regular way you would pass a variable through a function: void seta(int a) { a = 10; } int main() { int a = 5; seta(a); cout << a; //output is 5, because the function created a copy of variable a from main } Pass by reference is when you pass through a variable when the function parameters are that of a memory address using the ampersand (&): void seta(&a) { a = 10; } int main() { int a = 5; seta(a); cout << a; //output is 10, as we passed by reference, allowing the function to modify the variables memory address, rather than creating a copy and modifying that }
15th Sep 2016, 5:14 PM
Cohen Creber
Cohen Creber - avatar
+ 1
call by value: the value of the variable is copied when passed call by reference: the parameter is a reference to the variable passed, and the variable can be modified directly through it. An example of call by reference: void swap(int &a, int &b) { int tmp; tmp = a; a = b; b = tmp; } This function swaps the value of two variables.
15th Sep 2016, 5:13 PM
Zen
Zen - avatar
0
in caal by value we pass value as a variable. while in caal by reference we pass the address as a refernce
16th Sep 2016, 11:24 AM
Ankit Panwar
Ankit Panwar - avatar