A reference is just a “fancy [[Pointer]]” in [[C++]] and [[Rust]], that is an abstraction over a [[Pointer]].
Just as a [[Pointer]] *points* to a value of some type $T$, a reference *refers* to a value of some type $T$.
There is a slight shift in perspective going from using a [[Pointer]] to using a Reference.
>[!important]
*When using a [[Pointer]]*,
>>you are referring to an *integer address* to some $T$.
>
>
>
>*When using a Reference*,
>>you are referring to some *existing value* of $T$.
References are an abstraction of pointers in which hides the fact you are talking about an address. Whenever you use a reference in some [[Expression]], it will always mean you are trying to use the *value you are referring to*. With a [[Pointer]], it’ll assume you are referring to the *address of that value*.
One byproduct of this is that because References are always associated with a value:
- They cannot be null (see [[#Invariants]])
- You cannot do pointer arithmetic.
>[!example]
> Notice how when using pointers, you are required to dereference the pointer to talk about the value it is pointing at.
>
>```cpp
>void set_to_half(int* num) {
> *num = *num / 2;
>}
>
>void set_to_half_ref(int& num) {
> num = num / 2;
>}
>
int main() {
> int num = 420;
> set_to_half(&num); // explicitly get the reference of ‘num’
> set_to_half_ref(num); // takes a reference, so it gets a reference of ‘num’
> return 0;
>}
>```
### A note on Conversion
If you ever want to convert $T \mathbf* \to T\mathbf \&$, the syntax in [[C++]] would look something like this:
```cpp
int a = 0;
int* ptr = &a;
int& ref = *ptr;
```
While this may look like you are copying the value located at [[Pointer]], keep note that to set a reference you need to refer it to some *value*. You are simply saying in the expression that this reference equals to this *value* at this [[Pointer]], hence we need the dereference operator to talk about the *value* at this pointer.
### Invariants
References have one core [[Invariant]], all references of type $T\text{\&}$ refer to a valid $T$.
>[!example] Compiler error on trying to make an invalid reference
![[Pasted image 20240213194144.png]]
This means you can *never* have an uninitialized reference.