In the following code, both amp_swap() and star_swap() seems to be doing the same thing. So why will someone prefer to use one over the other? Which one is the preferred notation and why? Or is it just a matter of taste?
#include <iostream> using namespace std; void amp_swap(int &x, int &y) { int temp = x; x = y; y = temp; } void star_swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } int main() { int a = 10, b = 20; cout << 'Using amp_swap(): ' << endl; amp_swap(a, b); cout << 'a = ' << a << ', b = ' << b << endl; cout << 'Using star_swap(): ' << endl; star_swap(&a, &b); cout << 'a = ' << a << ', b = ' << b << endl; return 0; }
Thanks for your time!
See Also
One is using a reference, one is using a pointer.
I would use the one with references, because you can’t pass a NULL reference (whereas you can pass a NULL pointer).
So if you do:
Your application will crash. Whereas if you try:
Always go with references unless you’ve got a good reason to use a pointer.
See this link: http://www.google.co.uk/search?q=references+vs+pointers