References

A reference is essentially an alias to an existing variable. A variable declared by reference to another variable is essentially an alternative name to access the space allocated to the original variable. The & operator is used to declare variables by reference:

int x = 42;
int& y = x;

After writing the above, what do you think will be the output for the following code?

y = 0;
cout << x;

<aside> ⚠️ Note that references have to be initialized at the time of declaration, otherwise you would get an error at the time of compilation. Also, references once declared cannot be reassigned, and they also cannot be "nested" (in other words, it is not possible to have a reference to a reference).

</aside>

Passing values by reference in functions

Let's revist the example of swapping of two variables via function:

#include <iostream>
using namespace std;

void swap(int &a, int &b){
	int temp = a;
	a = b;
	b = temp;
	return;
}

int main(){

	int x = 10, y = 20;
	cout << x << " " << y;
  cout << endl;
	swap(x,y);
	cout << x << " " << y;

}

In the example above, what got passed was values of x and y, but the function drew them in as references, and updated the original values. In particular, when swap was called, what effectively happened was the following:

int &a = x;
int &b = y;

So a is essentially a reference to x, and b is a reference to y.

You can achieve the same effect by passing addresses and setting up the function to expect pointers instead of references, as we will see in the next section.

Pointers

For every datatype in C++, there is another datatype that stores a memory address of variables of a given type. How you declare a pointer, therefore, depends on the kind of variable that you want the address for.

Syntax: <datatype> <name>;*

int* x;
int *y;

Every variable stores its value someplace in the computer's memory. When you print a variable, you print the value that's stored in it. But if you want to know the address of the place where the variable is stored, then you need a pointer.

Since you don't explicitly assign the address yourself in the program, you need to use the built in operator & to recover the address assigned to the variable by the compiler.

#include <iostream>
using namespace std;

int main(){
    int x = 42;
    int *ptr = &x;
    cout << ptr << endl << &x;
}