Next Generation Emulation banner

Difference between reference and pointers.

1329 Views 6 Replies 5 Participants Last post by  Syed Fawad
I tried to search the web but I am kinda having difficulty in finding some "basic" difference between these two in layman terms.

POINTER:

int A;
int *pA;
pA = &A;

REFERENCE:

int A;
int &rA = A;

So what?

A is the name of the address of 2 bytes reserved in memory for integer type.
pA is the pointer which contains the address of A.
So what would rA be?
1 - 1 of 7 Posts
Passing by reference doesn't pass a copy of the variable, it passes a reference to the variable. As you clearly realized this means that changing the value in the called function will result in it being changed in the caller's variable space. In your example this would print 3..

References are "safe" pointers. They must always refer to either a valid object or explicitely nothing (the exception to this exists in a language that allows or requires explicit deallocation of memory, in which case what a reference refers to may become invalid. In such a case it's more correct to say that a reference can only be explicitely bound to something that exists at the time or to nothing at all, such as null in Java). In C you can use pointers as references but that requires pointer notation to dereference them. This can get pretty ugly, but occasionally it's nice to be very aware of exactly what layers of abstraction you're jumping through.

Pointers in C can point to any numeric memory location in the program's address space. You can't directly set it this way (without a cast), so even pointer arithmetic should retain alignment, but just the same there's no mechanism in C to stop you from incrementing a pointer into a region where no such object exists.

Pointers aren't necessary in just about any application that's sufficiently abstracted from the machine and OS kernel, and in those cases where they are you possibly have to coerce the language to allow for it (casting in C/C++). References make certain optimizations and garbage colllection troublesome but pointers make these just about impossible.

In general, references > pointers

- Exo
See less See more
1 - 1 of 7 Posts
This is an older thread, you may not receive a response, and could be reviving an old thread. Please consider creating a new thread.
Top