Skip to main content
GameDev.net gamedev.net
🔒 Locked

Cool Trick

Started by Lerner May 27, 2006 at 2:59 AM 9 replies 1.1k views
Original Post
Lerner
Lerner
I came across this trick for swapping...any comments? x = x+y -(y=x) ;
Sneftel
Sneftel
Ah. Yet another iteration of the Swap Without A Temporary game.

The problems:

* Creating a temporary value on the stack is "free" anyways.
* This introduces numerous data dependencies, leading to pipeline stalls and reduced performance.
* Swaps do not take a significant amount of time in most code.
* Readability is important.
* If this were the best way to do it, why would your compiler's implementation of std::swap not do it this way?
Lerner
Lerner
Is there any sequence point problem in that?
rpg_code_master
rpg_code_master
x ^= y ^= x ^= y;

I actually got asked that question at an interview once. It's so usful to know
Lerner
Lerner
Quote:
Original post by rpg_code_master
x ^= y ^= x ^= y;

I actually got asked that question at an interview once. It's so usful to know


Above code has undefined behaviour. Can anyone tell me about my original code. Is it also undefined?
Lerner
Lerner
*bump*
Brother Bob
Brother Bob
Is the leftmost y in the equation's right hand side evaluated before or after the assignment of y? The standard does not say, so yes, it's undefined.

edit: And to demonstrate that, here's a test case.
void swap(int &x, int &y){	x = x+y -(y=x);}int main(int, char **){	int a = 42;	int b = 10;	cout << "a = " << a << ", " << "b = " << b << endl;	swap(a, b);	cout << "a = " << a << ", " << "b = " << b << endl;}

Output from MSVC8 (both debug and release).
a = 42, b = 10a = 42, b = 42

Output from G++ (g++ test.cpp).
a = 42, b = 10a = 10, b = 42

Lerner
Lerner
Thanks Bro
Troll
Troll
Quote:
Original post by Lerner
Quote:
Original post by rpg_code_master
x ^= y ^= x ^= y;

I actually got asked that question at an interview once. It's so usful to know


Above code has undefined behaviour. Can anyone tell me about my original code. Is it also undefined?


You are incorrect. The original code exhibits undefined behavior. This code's behavior is defined. The evaluation will proceed from the right hand side to the left.
Enigma
Enigma
Both are undefined. The OPs because of undefined order of evaluation of parameters and the xor swap because scalar objects may not have their values modified more than once by the evaluation of an expression without intervening sequence points (C++ Standard, Final Draft, Section 5, Paragraph 4).

Σnigma

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.