You could say that a reference is a pointer that behaves like the var itself. You can use a variable given as argument in a function like a variable,and it will change the original variable like it was a pointer.
Its like a trick for if you want to use pointers but don't want to be confronted with the pointer directly.
Got it ? X-)
Greetz,
1.) a constant pointer (i.e. it always points to the same object) that
2.) automatically takes the address of the object used to initialize it and
3.) automatically dereferences itself when used.
A variable that holds an address in memory. Similar to a reference, however, pointers have different syntax and traditional uses from references.
Reference
A variable that holds an address in memory. Similar to a pointer, however, references have different syntax and traditional uses from pointers.
You can assign pointers to "point to" addresses in memory
You can assign references to "refer to" variables or constants
You can copy the values of pointers to other pointers
You can modify the values stored in the memory pointed to or referred to by pointers and/or references, respectively
You can also increment or decrement the addresses stored in pointers
You can pass pointers and/or references to functions
When declaring a pointer to an object or data type, you basically follow the same rules of declaring variables and data types that you have been using, only now, to declare a pointer of SOME-TYPE, you tack on an asterix * between the data type and its variable.
int m;
int* x;
x = &m;
To declare a reference, you do the exact same thing you did to declare a pointer, only this time, rather than using an asterix *, use instead an ampersand &.
int &x; // incorrect !!
// a reference must be initialized. Hence, it should be
int &x = i; // i must be a variable one can not write int &x = 10;
once you define a variable, you can not assign it to some one else i.e.
int &x = j; // wrong.
//however, if j has some value, you can do
x = j
if you change the value of x later, value of i would also be changed.
If you change the value of i later, value of x would also be changed,
reference is an alias, hence, x and i would refer to same thing in the memory.
So,
x = 10 would change value of x to 10 and i to 10.
Also, if you now do i = 20, value of i would be 20 and that of x would be 20 again.
You know a pointer contains an address, right? When you dereference a pointer (which is like having int *ptr and saying *ptr), you get the piece of data contained in that pointer's address.
For example:
int integer = 7; // an int initialized to 7
int *p = &integer; // a pointer initialized to the
// address of "integer"
*p = 4; // "p" is dereferenced;
// "*p" is the value contained in "p"
// which is "integer" in this case.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.