Hi,
So I have an assignment to do and it goes as follows.
Write a simple program which reads in 2 integers, a & b, from cin.
print out the values they entered, a & b
Pass a & b *by reference* to a function which will *swap* their values
Return back to main() and print out a & b again, showing that their values have been swaped.
First, you should give your functions meaningful names, not misleading ones. Here's how you could write that function:
1 2 3 4 5 6
void swap_values(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
You should notice a few things you were getting wrong. A reference acts exactly like the original object. There's no need to dereference it (and, to dereference a pointer, you say *ptr, not ptr*). Also, a function has no way of knowing about non-local, non-global variables (I'm ignoring class members for now).
Finally, what were you thinking by assigning some variable to b/a or a/b? That's certainly not swapping!
Yeah, I was confused, I was figuring that using a division of the numbers would swap their values, hence the a/b b/a stuff. And thank you guys for the help. Here is what I have now,
#include <iostream>
using namespace std;
void swap_values (int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
int main ()
{
int x, y;
cout << "Enter first number: ";
cin >> x;
cout << "Enter second number: ";
cin >> y;
cout << "x = " << x << endl;
cout << "y = " << y << endl;
return 0;
}
Im still a little confused as to how the the swapped values get printed
The assignment states:
Write a simple program which reads in 2 integers, a & b, from cin.
print out the values they entered, a & b
Pass a & b *by reference* to a function which will *swap* their values
Return back to main() and print out a & b again, showing that their values have been swapped.