The context is different. * and & mean different things depending on the context.
1 2
int * pointer, p; // declare a pointer "pointer", and a regular variable
pointer = &p; // store the memory location of p in pointer
1 2
int& pointer, p; // this doesn't even compile for me.
pointer = p;
You use references like that in function parameters list...
1 2
int function(int &a) // normally "a" would get copied, but in this case it won't be
{ /* ... */ }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
int function(int &a)
{
a = 5;
}
int main()
{
int b = 32;
std::cout << b << std::endl;
function(b);
std::cout << b << std::endl;
return 0;
}
#include <iostream>
usingnamespace std;
int main(){
//an integer
int myInt = 0;
//pointer to integer in stack
int * pInt;
//pInt now points to myInt
//pInt = &myInt; means "give me the memory address of myInt and assign it to pInt
pInt = &myInt;
//now whatever you do with the pointer, is done to myInt
*pInt = 24;
cout << "myInt now: " << myInt << endl;
//above, *pInt = 24; means "assign 24 to the location of pInt"
//where, myInt sits. so, we're changing myInt's value explicitly.
//this is a reference to myInt
// int & rMyInt = myInt; means "create an alias for myInt"
// whatever you do will be don to myInt
int & rMyInt = myInt; //we have to initialize references immediately
cout << "rMyInt: " << rMyInt << endl;
cout << "myInt : " << myInt << endl;
//lets play with it
rMyInt = 88;
cout << "rMyInt: " << rMyInt << endl;
cout << "myInt : " << myInt << endl;
/*
output of this program:
myInt now: 24 -->line 18
rMyInt: 24 -->line 27
myInt : 24 -->line 28
rMyInt: 88 -->line 33
myInt : 88 -->line 34
*/
return 0;
}