Jump to content
  • Advertisement
Sign in to follow this  
Joshuad

Problem passing references

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

If you intended to correct an error in the post then please contact us.

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 badSwap(int x, int y);
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 << "Calling badSwap()\n";
	badSwap(myScore, yourScore);
	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 this post


Link to post
Share on other sites
Advertisement
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..

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!