8. References and Pass by Reference #
Created Wednesday 25 December 2019
- We want to make a variable name(an alias, not a pointer) with the address of a variable. This new variable name does not have a memory of its own. It is just an alias for an existing variable.
- It is just a record in the symbol table. A record which copies the address and data type. (Data type needs to be same).
Syntax:
int x = 10;
/*declaration*/ int &y = x; // reference is not a pointer, it's an alias, so no need of assigning the address.
/* value reassignment*/ alias_1 = alias_2; //allowed, just copies data from alias_2 to alias1's variable.
/* access/modification */ alias1++; // exactly the same as the original name . (Nothing like derefence here).
/*function declaration*/ f(int &x);
/* passing a variable as reference*/ f(p); // interpreted as int &x = p; so no problems.
Note:
- References ‘sources’ cannot be reassigned. As they are in the symbol table. No change can be made in the symbol table, once written.
Caution: int x = 10; int &y; // invalid You requested for an alias, but for what? Absurd/Error. Remember that we have to fill all fields in the symbol table and that they are unchangeable. Although values(i.e at memory location), can be changed.
- Hence reference variables need to be initialized at the time of declaration.
Advantages of reference variables(i.e why are they useful):
- We don’t need to make pointers for each function call where we need to make changes to the same memory, during function calls.
- No extra storage required. Good for memory.
- Code is short and clean.
Normal variable and a reference are interchangeable #
void f(int val)
{
val++;
}
void g(int &val)
{
val++;
}
main()
{
int a = 5;
int &b = a;
f(a); // OK
f(b) ; // OK
g(a); // OK
g(b); // OK
// all combinations are OK
}
Note: As we can send values(by reference), we can recieve values as well. Called return by reference. Caution: Return by reference and return by address are very dangerous, as they can sometimes return reference and address of local variables, which may have gone out of scope. It’s a bad practice. https://www.bogotobogo.com/cplusplus/memoryallocation.php