A Little Trouble with Deference operator?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace 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.
Last edited on
BlackSheep so at that point it has nothing to do with a memory address at that point when used in a function like that?
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).
This one is a c++ special (not available in c).

It's effectively just a short-hand version of:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace 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;
}
Thanks guys that makes sense now :)
Topic archived. No new replies allowed.