(&) question

My old instructor never used this symbol before, but my new one does. I have read the book on what it does, but do not understand why it is even useful...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

void increment(int &n)
{
  n++;
  cout << "\tThe address of n is " << &n << endl;
  cout << "\tn inside the function is " << n << endl;
}

int main()
{
  int x = 1;
  cout << "The address of x is " << &x << endl;
  cout << "Before the call, x is " << x << endl;
  increment(x);
  cout << "after the call, x is " << x << endl;

  return 0;
}


Why not just do this...why would we even use the (&)?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

void increment(int n)
{
  n++;
  cout << "inside the function is " << n << endl;
}

int main()
{
  int x = 1;
  cout << "The address of x is " << &x << endl;
  cout << "Before the call, x is " << x << endl;
  increment(x);
  cout << "after the call, x is " << x << endl;

  return 0;
}
Have you checked the output of each piece of code? There is a crucial difference.
&x is a pointer to x.
Pointers are very useful, you could also do this:
1
2
3
4
5
6
7
8
9
int x = 23;
int *xPtr;

xPtr = &x;

x = 76;

cout<<"x == "<<x<<endl;             // 76
cout<<"*xPtr == "<<*xPtr<<endl; // also 76, the * dereferences the pointer 
I see what is going on. It seems to me like the "&" is like a scope..in a way.
I see what is going on. It seems to me like the "&" is like a scope..in a way.

I don't think so.

Check out: http://cplusplus.com/doc/tutorial/pointers/

Also, not trying to confuse you, but just so you are aware, & is also used for 'references' and it is easy to confuse the two. They can be used in a similar way.
1
2
3
4
5
void myFunction(int *ptrArg, int &refArg)
{
*ptrArg = 6;
refArg = 6;
}

1
2
3
int x = 55;
int xPtr = &x;
int &xRef = x;
Last edited on
In your case, it is a reference. This means that when you pass "x" to the function, you are modifying the *actual* "x", not a copy. This allows you to change the variable inside the function (like in the first piece of code you showed the function will add one to the actual x variable).
Ah, just noticed you are actually using & in both ways.
1
2
3
4
5
6
void increment(int &n)     // Here it says that the variable is passed as a reference
{
  n++;
  cout << "\tThe address of n is " << &n << endl;        // Here it is the pointer, or the address space
  cout << "\tn inside the function is " << n << endl;
}
Topic archived. No new replies allowed.