If we have this code:
int foo=100;
int& reference = foo;
int* pointer = &reference;
There's no actual binary difference in the reference's data and the pointer's data. (they both contain the location in memory of foo
)
part 2
So where do all the other differences between pointers and references (discussed here) come in? Does the compiler enforce them or are they actually different types of variables on the assemebly level? In other words, do the following produce the same assembly language?
foo=100;
int& reference=foo;
reference=5;
foo=100;
int* pointer=&foo;
*pointer=5;
References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference.
Pointers are variables; they contain the address of some other variable, or can be null. The important thing is that a pointer has a value, while a reference only has a variable that it is referencing.
A reference to a pointer is a modifiable value that's used like a normal pointer.
Reference vs Pointer in C++. As a rule of thumb, passing by reference or pointer is typically faster than passing by value, if the amount of data passed by value is larger than the size of a pointer. . In this case, they are equivalent. References have clearer semantics.
Theoretically, they could be implemented in different ways.
In practice, every compiler I've seen compiles pointers and references to the same machine code. The distinction is entirely at the language level.
But, like cdiggins says, you shouldn't depend on that generalization until you've verified it's true for your compiler and platform.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With