- One variable can have multiple references
- But a reference can refer to only one variable in its life time.
- Reference needs to be initialized (declared and defined in same line).
- You can't do int i; int &ref; ref = i;
- int i; int &ref = i;
- Reference are so tightly coupled that any change in one reflect in change in all others
Example:
int i = 10;
int &ref = i;
void funct_r(int &ref);
void funct_v(int val);
void funct_a(int *add);
...
...
main() {
int i = 10;
funct_r(i); // call by reference
funct_v(i); // call by value
funct_a(&i);
}
reference are more readable than pointers while for most part they work like pointers. Btw, it is also possible to create reference to a pointer.
e.g.
char *name = "India";
char *& ref = name; // Read from right to left... it says reference to a char *
Points to remember:
Points to remember:
- We cannot have a array of references
- Never return local variable by reference
No comments:
Post a Comment