Lesson 16 Swap() Function The Easy Way

The Partridge Family were neither partridges nor a family. Discuss.
Post Reply
adabo
Posts: 154
Joined: October 27th, 2012, 3:28 am
Location: Houston, Texas

Lesson 16 Swap() Function The Easy Way

Post by adabo » October 31st, 2012, 12:01 am

*Edit: Fellow students, this is not a substitute to Chili's lesson. Follow the thread for more info*

I don't know if this is the right or wrong. Allow me to explain.

So I paused the video when the Chili first showed the Swap() function not working and thought about it. Coming from a highlevel scripting language I already know a method to fix it so I tried it and it worked.

Instead of adding a bunch of pointer references, I just referenced the input arguments. 2 ampersands to fix the code:

Code: Select all

void Swap(int &x1, int &x2){
		int temp = x1;
		x1 = x2;
		x2 = temp;
}
So there you have it. It worked for me, maybe it works for you. You don't have to change anything on the Swap(); call. Just call it like you normally would:

Code: Select all

Swap(x1, x2)
And away you go.

My question to the pros is, why /not/ use this method? Is there a disadvantage? Thanks.
Last edited by adabo on November 2nd, 2012, 5:35 pm, edited 2 times in total.

Muttley
Posts: 39
Joined: October 19th, 2012, 6:00 am

Re: Lesson 16 Swap() Function The Easy Way

Post by Muttley » October 31st, 2012, 4:23 am

What are you using is called Reference, I think its better to this situation, but Chili wanted to show us a example of how pointers work. :)
He explains how it works here -> http://www.youtube.com/watch?feature=pl ... sE#t=1321s

User avatar
chili
Site Admin
Posts: 3948
Joined: December 31st, 2011, 4:53 pm
Location: Japan
Contact:

Re: Lesson 16 Swap() Function The Easy Way

Post by chili » October 31st, 2012, 2:25 pm

Yeah, what muttley said. ;)

Actually references and pointers are really the same thing under the hood. It's just syntax and restrictions that make the difference. And yes, if I were not trying to teach a specific concept and just trying to make a swap function, I would use references too. I use them a ton in the intermediate series once we get started on the platformer game.
Chili

adabo
Posts: 154
Joined: October 27th, 2012, 3:28 am
Location: Houston, Texas

Re: Lesson 16 Swap() Function The Easy Way

Post by adabo » October 31st, 2012, 5:14 pm

ohhh.. yeah. I knew I had a feeling I was jumping ahead here.

@Chili: I certainly don't want to confuse anyone by this post and I don't have the intention of deviating from your teaching. After all I'm really a total noob here.

@Muttley: Thanks for the link :)

Re-reading my post I feel I come across a little arrogant, and that's just not what I meant. Shallow highlevel scripting is no comparison to a powerful lowlevel c++ language. Just in case anyone took that the wrong way ;)

Post Reply