Which one is better: Pass by Reference using void increment(int& x)
or Pass by Pointer using void increment(int* x)
?
void increment(int& x)
{
x=x+1;
}
int main()
{
int n= 2;
increment(n);
cout << "Value of n is " << n << '\n';
return 0;
}
or
void increment(int* x)
{
*x=*x+1;
}
int main()
{
int n= 2;
increment(&n);
cout << "Value of n is " << n << '\n';
return 0;
}
None is better. The advantage of using pointer is that it makes explicit in the calling code that the argument is passed by pointer, since the argument is preceded with &
. The advantage of using reference is that it is more natural in the calling function code, without all *
dereferences. Internally the are normally implemented in the same way, so there should be no speed advantages.