0

Why is there sometimes the & operator inside the parameters of a function?

31st Jul 2016, 1:28 PM
jigoku_tenshi
4 Respostas
+ 3
void setA(int &a) { a = 6; } int main() { int a = 5; cout << "a = " << a << "\n"; setA(a); cout << "a = " << a << "\n"; } Here is an example. When we pass a through setA, we pass it by reference, because the arguements of the function is &a (the memory address of a). We then set a to 6. And even if we didn't return a from setA, the a in the main evaluates to 6. If we didn't include the & operator in the arguements, then a = 6 will only be true inside the function, whereas in main, a will still be 5. Sorry if this is confusing, my explaination is a bit shit.
31st Jul 2016, 3:10 PM
Cohen Creber
Cohen Creber - avatar
+ 2
The andersand (&) operator returns the memory address of an object or a variable. When used passing variables in a function e.g. int func(int &a, int &b) this is called pass by reference, and allows you to modify the original variable that was passed through. When using pass by value (without the &), you are creating temporary variables inside that function, which do not effect the original variables.
31st Jul 2016, 2:08 PM
Cohen Creber
Cohen Creber - avatar
0
What do you mean by original variables?
31st Jul 2016, 2:46 PM
jigoku_tenshi
0
It makes sense. Great explanation! So if I wanted to print 5 without removing the &, all I'd have to do is print *p in the cout?
31st Jul 2016, 3:42 PM
jigoku_tenshi