Swapping values

Started by
13 comments, last by Zorbfish 21 years, 10 months ago
quote:Original post by theNestruo
/*How to swap two integers in just one line*/a^=b^=a^=b;  

It''s cool, isn''t it?


Plain evil. It will fail if both a and b are the same variables. Don''t ever make this swap to a macro or inline function.
Advertisement
quote:Original post by theNestruo
It''s cool, isn''t it?

No, it''s undefined behaviour, since you are modifying a variable more than once without an intervening sequence point.
This has been discussed at length before ( swapping variables )... Do a search, you''ll come across it.

I remember benchmarking various techniques for swapping variables, and the XOR version was the slowest. Four mov was the quickest, followed by the xchg instruction ( I think ), and then a temp variable... I can''t quite remember, look up the thread for more info.

Death of one is a tragedy, death of a million is just a statistic.
If at first you don't succeed, redefine success.
Thanks... I have the idea of what I need to do... from the looks of things I did have the right idea about swapping... I needed it for a puzzle game Im making where you swap blocks around to score points... I asked about the moving rows/cols because I was thinking of adding a row of randomly chosen blocks to the bottom of the array everytime a set timer goes off. So I needed a way to shift all the existing blocks up the array to make an empty bottom row for the next set...
quote:Original post by python_regious
I remember benchmarking various techniques for swapping variables, and the XOR version was the slowest. Four mov was the quickest, followed by the xchg instruction ( I think ), and then a temp variable


Interesting, I was under the assumption that bitwise operations were fast, faster than using a temp var, especially when used to swap variables.

This topic is closed to new replies.

Advertisement