8. References and Pass by Reference #

Created Wednesday 25 December 2019

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:

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.

Advantages of reference variables(i.e why are they useful):

  1. We don’t need to make pointers for each function call where we need to make changes to the same memory, during function calls.
  2. No extra storage required. Good for memory.
  3. 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