In C++ instead of using pointers we use references. To use a reference use the & sign before the varible name. If we replace pointer with references we will get:
voidswap(int&a,int&b){int t = a; a = b; b = t;};intmain(){int a=1, b=2;swap(a,b); cout <<"a: "<<a<<", b:"<<b;}
References vs Pointers
Even though similar there are differences. A pointer can be declared as void but a reference can never be void
3 differences:
Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
A reference must be initialized when declared. There is no such restriction with pointers
References are safer and easier to use:
Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist.
Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. ‘&’ operator is needed only at the time of declaration