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
int& is a reference to int variable. Reference is something very close to the pointer. The main difference is that the reference is constant, so it should be assigned immediately after initialization and you can do no pointer arithmetics with reference.
INT(x) rounds the number x down to an integer.
&a means "address of a" only when used outside function declarations.
A int& return type simply means it returns a reference (address) of an EXISTING integer variable, same goes for int& as an argument, the function takes a reference to an integer instead of creating a new variable copy of it.
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:
star_swap(NULL, NULL);
Your application will crash. Whereas if you try:
amp_swap(NULL, NULL); // This won't compile
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With