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...
#include <iostream>
usingnamespace 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>
usingnamespace 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;
}
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.
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;
}