Similar to passing arguments by reference, we can also pass arguments by address. For example,
#include <iostream>
void printInt(const int *ptr)
{
std::cout << *ptr << "\n";
}
int main(int argc, char const *argv[])
{
int value{5};
printInt(&value);
return 0;
}printInt takes parameter of type int pointer-to-const and we pass address of value using address-of operator.
Eliminate copying arguments
One advantage of passing by address is that it does not copy the value of passing argument, it just copies the pointer which is an inexpensive operation.
For example, passing an argument of type std::string does an expensive copy operation. If we pass it using address, we eliminate the copy operation.
Allows modifying function arguments
We can modify the value of the object pointer is pointing using dereferencing which can be useful in some scenarios. However, it is always advisable for a function to not modify the arguments.
We can achieve this by making using pointer-to-const as shown our first example.
Always do null checking
If a function accepts a pointer, always do a null checking for null pointer before dereferencing as it may be cause the program to crash.
For example,
void printInt(const int *ptr)
{
if (!ptr)
return;
std::cout << *ptr << "\n";
}