We’ve seen the benefits of passing variables by reference to a function. It allows you to change their value inside the function. Well, when we pass by reference, this is essentially using pointers – you just didn’t realize it.
Therefore you can have instances like:
void swap(int* x, int* y)
{
int* temp = x;
x = y;
y = temp;
}
int main()
{
int x = 5;
int y = 10;
cout << x << endl;
cout << y << endl;
swap(x, y);
cout << x << endl;
cout << y << endl;
return 0;
}
Alternatively I can write it with passing the memory address and references.
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int x = 5;
int y = 10;
cout << x << endl;
cout << y << endl;
swap(&x, &y);
cout << x << endl;
cout << y << endl;
return 0;
}
Passing Pointers to a Function was originally found on Access 2 Learn