Hi,
I need to swap a couple of integers in the format int i[2]
using a void swap(int& x)
function. As you see the function takes an argument of type int&
. Here is non-working version of the function:
int i[2] = {3, 7};
void swap (int& x)
{
int temp;
temp = x[1];
x[1] = x[0];
x[0] = temp;
}
int main()
{
cout << i[0] << ", " << i[1] << "\n"; // return the original: (3, 7)
swap(i);
cout << i[0] << ", " << i[1] << "\n"; // return i swapped: (7, 3)
}
How should I do this?
Edit: The answer CANNOT use anything else for the function parameter. It MUST use a int&
parameter. This is a problem from Bjarne Stroustrup's book: "The C++ programming language", third edition. It is problem #4 from chapter 5. The problem first asks to write a function taking a int*
as parameter, than to modify it to accept a int&
as parameter.