Pointers VS References
C and C++ support pointers which are different from most of the other programming languages. Other languages including C++, Java, Python, Ruby, Perl and PHP support references.
On the surface, both references and pointers are very similar, both are used to have one variable provide access to another. With both providing lots of the same capabilities, it’s often unclear what is different between these different mechanisms. In this article, I will try to illustrate the differences between pointers and references.
* A pointer can be declared as void but a reference can never be void
Example:
int a = 10;
void* aa = &a;. //it is valid
void &ar = a; // it is not valid
* References are less powerful than pointers
* Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
* References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
* A reference must be initialized when declared.There is no such restriction with pointers.
There are two ways to pass arguments to a function as the function is being called.
🔙... 🔜
On the surface, both references and pointers are very similar, both are used to have one variable provide access to another. With both providing lots of the same capabilities, it’s often unclear what is different between these different mechanisms. In this article, I will try to illustrate the differences between pointers and references.
* A pointer can be declared as void but a reference can never be void
Example:
int a = 10;
void* aa = &a;. //it is valid
void &ar = a; // it is not valid
* References are less powerful than pointers
* Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
* References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
* A reference must be initialized when declared.There is no such restriction with pointers.
There are two ways to pass arguments to a function as the function is being called.
By value: This method copies the argument's actual value into the function's formal parameter. Here, we can make changes to the parameter within the function without having any effect on the argument.
By reference: This method copies the argument's reference into the formal parameter. Within the function, the reference is used to access the actual argument used in the call. This means that any change made to the parameter affects the argument.
🔙... 🔜
Comments
Post a Comment