FCI-Helwan blog

Just another FCI-H weblog

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

Advertisements

February 4, 2007 - Posted by | C/C++

2 Comments »

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

    Comment by Mohamed Gamal El-Den | February 4, 2007 | Reply

  2. 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.

    Comment by Mohammad Nabil | February 5, 2007 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: