#include <iostream>
usingnamespace std;
void add(int& a, int& b)
{
a+=2;
b+=2;
}
int main()
{
int x = 2;
int y = 9;
add(x,y);
cout << x << "and" << y << endl;
system("PAUSE");
return 0;
}
So in the code above I know what it does but I'm not 100% understanding why it works.
When you start with the function
void add(int& a, int& b)
I thought that & was read as them memory address of? How does that work like? The memory address of int a? and then x get's put into that? That wouldn't make sense. Does & mean something different when used inside of a function? Please explain? Thanks in advance
Using the dereference in a function parameter means that the value will be passed by reference. So changing it inside the function will change the initial value as well.
EDIT: I donno why I just thought of this, but for references sake, that's not the dereference operator.
* <- this is the dereference operator.
& <- is the address-of operator.
No, it has nothing to do with the address! It just means that any change done in the function to the variable(s) will be done in the main program too with those same variable(s).
#include <iostream>
usingnamespace std;
void add(int* a, int* b)
{
*a+=2;
*b+=2;
}
int main()
{
int x = 2, y = 9;
add(&x,&y);
cout << x << "and" << y << endl;
return 0;
}