This seemingly small code which swapps 2 numbers is giving me a headache..help!! C++
+ am wondering why would one need to swapp the numbers in real life? trickery? magic
dennis.ritchie
0
Newbie Poster
Recommended Answers
Jump to PostPlease show the code. Without that, it isn't possible to answer your question. The typical swap algorithm is this
swap(type& var1, type& var2) { type tmp = var1; var1 = var2; var2 = tmp; }
Jump to PostAre you talking about the xor-swap trick? Like this:
void swap(int& x, int& y) x ^= y; y ^= x; x ^= y; };
Jump to PostIt wasn't me who down-voted that post. But I can understand why: (1) just one line of code with no explanation is not very helpful, (2) the code is indeed wrong (undefined behavior), and (3) the corrected version of that code (Kristian_2's version) is still problematic due to overflow problems.
…
All 10 Replies
rubberman
1,355
Nearly a Posting Virtuoso
Featured Poster
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
mike_2000_17
2,669
21st Century Viking
Team Colleague
Featured Poster
rubberman
commented:
Elegant. The question is whether 3 xors is more efficient than one stack operation and 3 assignments... Probably! :-)
+0
Moschops
683
Practically a Master Poster
Featured Poster
Learner010
99
Posting Whiz in Training
rubberman
1,355
Nearly a Posting Virtuoso
Featured Poster
hasnat ahmad
0
Newbie Poster
Kristian_2
11
Light Poster
mike_2000_17
2,669
21st Century Viking
Team Colleague
Featured Poster
Kristian_2
11
Light Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.