In some comp-sci papers and tests, I see swap() implemented like so:
void swap(int x, int y, int *a)
{
int t = a[x];
a[x] = a[y];
a[y] = t;
}
Why not simply implement it like so:
void swap(int& x, int& y)
{
int t = x;
x = y;
y = t;
}
Is the idea to the former to make the calling code cleaner, by not having to index into the array for the first two arguments? I realize it's not a very important question, since we should be using std::swap(), but I'm still curious.
Not all programming languages support calling by reference. For instance, the latter way of doing swap
doesn't apply to Java.
In books containing pseudo-code, usually there's a convention that arrays and pointers are not copied when passed and everything else is copied in a function call. The former way requires no special explanation about the way arguments are passed.
Regarding your final point about cleanliness, it's not so much different: in the former case, your call to swap would be simply: swap(i, j, a);
whereas in the latter, you'll have to swap(a[i], a[j]);
, introducing some brackets in the expression.
Your second code sample is C++, NOT C. C++ supports reference parameters, but C only supports reference indirectly via pointers.
I agree that the second implementation is cleaner. In order to make it work in C, change the &
in each of the parameters to *
and dereference each x
and y
(also with *
) inside the function.
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