Public Group

Problem passing references

This topic is 3322 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I'm trying to do this exercise that teaches passing references, and it's not working quite like it should. I'm pretty sure it's because I'm trying to set these references up wrong, but I'm not 100% positive. badSwap() is supposed to show that variables can't be changed in functions, which is why you reference them, and goodSwap() is supposed to be the reference. This is from the first edition of Beginning C++ Game Programming from back in 2004...I don't have the money to update my copy, so I've been fixing a lot of code, which has been a better learning experience for me than the latter. Here is the code that I have:
// Swap
// Demonstrates passing references to alter argument variables

#include <iostream>

using std::cout;

void goodSwap(int& x, int& y);

int main()
{
int myScore = 150;
int yourScore = 1000;
cout << "Original values\n";
cout << "myScore: " << myScore << "\n";
cout << "yourScore: " << yourScore << "\n\n";

cout << "myScore: " << myScore << "\n";
cout << "yourScore: " << yourScore << "\n\n";

cout << "Calling goodSwap()\n";
goodSwap(myScore, yourScore);
cout << "myScore: " << myScore << "\n";
cout << "yourScore: " << yourScore << "\n";

return 0;
}

void badSwap (int x, int y)
{
int temp = x;
x = y;
x = temp;
}

void goodSwap (int& x, int& y)
{
int temp = x;
x = y;
x = temp;
}


Anyone got any ideas?

Share on other sites
Your last line should read y = temp, not x = temp.

Share on other sites
Wow, of all the silly things I could have done, I didn't think something like that would be it. Thanks a lot. *slaps self*

It works now, by the way..

• 11
• 20
• 12
• 10
• 34
• Forum Statistics

• Total Topics
631399
• Total Posts
2999854
×