This blog is subject the DISCLAIMER below.

Sunday, February 04, 2007

Differences between Pointers and References

1- Reference must be initialized and assigned to the object it references to, like

int &ref_integer ; // error




int number;

int &ref_integer = number; // right

pointers have not to point to something when declared, it’s enough to mention to which type it points

int *p_integer; // right


But also in reference you do not need to mention to which object or variable it references iff (if and only if) you make it external

int &ref_integer ; // error

extern int &ref_integer ; // right

2- Reference can not be reinitilized
int number, anotherNumber;

int &ref_integer = number; // right


&ref_integer = anotherNumber; //error


where pointer can be.

int number, anotherNumber;


int* p_integer;

p_integer = &number;


p_integer = &anotherNumber;


3- ‘&’ operator when is used with reference it returns the address of the variable the reference references, like

int integer;

int &ref_integer = integer;


cout<<&integer<<endl; // prints XXXXXXX

cout<<&ref_integer<<endl; // prints XXXXXXX


but in pointers, when ‘&’ operator is used it references to the address of the pointer not the address of the varible it poitns to
int* p_integer;

p_integer = &integer;

cout<<&integer<<endl; // prints XXXXXXX

cout<<&p_integer<<endl; // prints YYYYYYY


2 comments:

Mohamed Gamal El-Den said...

Well Done Ramy , but Plz Explain the extern Key Word . Thanks

Mohammad Nabil said...

an external variable means that it does exist (and in this case, been initialized) in another file. Refere to the linking article for more details.