+ 2

What is the call-by-value in c++? Please I need to understand it carefully. Thanks.

3rd Jun 2018, 1:11 PM
sayed sayed
sayed sayed - avatar
4 Answers
+ 4
There's basically a call by value and a call by reference, both of them are important to know In a nutshell, when you make a function that calls on value it will not change the parameter, but if you call it on a reference it will change the parameter. for an example, let say we have a function that is called by value int f(int n) {n = n+2; return n;} and in the main program we'll have int main(){ int a = 3; cout << f(a) << endl; cout << a; } it will output 5 3 so the 'a' will not be changed But when you called it by reference, like this int f(int &n){ n = n+2; return n;} int main(){ int a = 3; cout << f(a) << endl; cout << a; then it will output 5 5 You can learn more to understand it on the internet, such as here https://youtu.be/4oKa-ZKaIcY *note: I'm a beginner myself so I'm sorry if this wasn't true or wasn't clear enough
3rd Jun 2018, 1:26 PM
Muhammad Hasan
Muhammad Hasan - avatar
+ 2
it means that the value gets copied into a variable that is visible in the scope of the function you are calling: example: void func(int i){} int main(){ func(1); } 1 gets copied into i if you do void func(int& i) a reference(basically the memory adress) to 1 gets copied into the function typicaly you would use call by value for types that can be copied fast and call by reference for types that cant be copied fast
3rd Jun 2018, 1:21 PM
Max
Max - avatar
+ 2
example of passing by value vs by reference https://code.sololearn.com/ckFKDRje4kGV/?ref=app
3rd Jun 2018, 1:38 PM
ifl
ifl - avatar
0
thank you alot🌾
3rd Jun 2018, 1:24 PM
sayed sayed
sayed sayed - avatar