Upcoming Posts

Upcoming Posts....

Make your own partition magic software.
How to make an assembler.
What is booting?
Write a simple OS!

‎"I have no special talents. I am only passionately curious." - Albert Einstein

Monday, January 2, 2012

Reference vs. Pointer

A reference is an alternate name for an object/variable. Reference is an implicit constant pointer to a variable. It can’t be used to point memory location say 0x1000. On the other hand, pointers can be used to point to any location in the memory. To access any address, we'd need to use pointers instead of references.

Here is a simple example of reference/pointer.

int i = 10;

mov dword ptr [i],0Ah // dis-assembly code

Reference:

int &ref = i;

lea eax,[i] // disassembly code

mov dword ptr [ref],eax // dis-assembly code

int j = ref;

mov eax,dword ptr [ref] // dis-assembly code

mov ecx,dword ptr [eax] // dis-assembly code

mov dword ptr [j],ecx // dis-assembly code

Pointer:

int *ptr = &i;

lea eax,[i] // disassembly code

mov dword ptr [ptr],eax // dis-assembly code

j = *ptr;

mov eax,dword ptr [ptr] // dis-assembly code

mov ecx,dword ptr [eax] // dis-assembly code

mov dword ptr [j],ecx // dis-assembly code

If you see their dis assembly code, you can see that the dis assembly code generated for reference and pointer is same. This means that implementation wise they are same.

Use reference as much as you can as you don’t need to use & and * confusing operators J.