This one is even more succinct.
Declared variables, but only to reinterpret its type. I had to do this, because of floating point wide known precision problems.
Imho better to violate the letter of the rules a little, and obey the spirit, than pretending that something is equal, when it isn't.
#include <algorithm> #include <math.h> template< class T > void Swap( T& a, T& b ) { /* a = (reinterpret_cast<long long >(a) + reinterpret_cast<long long >(b)); b = (reinterpret_cast<long long >(a) - reinterpret_cast<long long >(b)); a = (reinterpret_cast<long long >(a) - reinterpret_cast<long long >(b)); */ long long plla = *((long long*) &a); long long pllb = *((long long*) &b); plla = plla + pllb ; pllb = plla - pllb ; plla = plla - pllb ; a =*((T*) &plla); b =*((T*) &pllb); }
- #include <algorithm>
- #include <math.h>
- template< class T >
- void Swap( T& a, T& b )
- {
a = a + b;b = a - b;a = a - b;- /*
- a = (reinterpret_cast<long long >(a) + reinterpret_cast<long long >(b));
- b = (reinterpret_cast<long long >(a) - reinterpret_cast<long long >(b));
- a = (reinterpret_cast<long long >(a) - reinterpret_cast<long long >(b));
- */
- long long plla = *((long long*) &a);
- long long pllb = *((long long*) &b);
- plla = plla + pllb ;
- pllb = plla - pllb ;
- plla = plla - pllb ;
- a =*((T*) &plla);
- b =*((T*) &pllb);
- }
Describe(Tests) { It(Swaps) { int a = 1, b = 2; bool c = true, d = false; double e = 3.14, f = 6.28; double e1= 1.43, f1= 1.435; Swap( a, b ); Swap( c, d ); Swap( e, f ); Swap( e1,f1); Assert::That( a, Equals(2)); Assert::That( b, Equals(1)); Assert::That( c, Equals(false)); Assert::That( d, Equals(true)); Assert::That( e, EqualsWithDelta(6.28, 0.1)); Assert::That( f, EqualsWithDelta(3.14, 0.1)); Assert::That( e1, Equals(1.435)); Assert::That( f1, Equals(1.43)); } };
- Describe(Tests)
- {
- It(Swaps)
- {
- int a = 1, b = 2;
- bool c = true, d = false;
- double e = 3.14, f = 6.28;
- double e1= 1.43, f1= 1.435;
- Swap( a, b );
- Swap( c, d );
- Swap( e, f );
- Swap( e1,f1);
- Assert::That( a, Equals(2));
- Assert::That( b, Equals(1));
- Assert::That( c, Equals(false));
- Assert::That( d, Equals(true));
- Assert::That( e, EqualsWithDelta(6.28, 0.1));
- Assert::That( f, EqualsWithDelta(3.14, 0.1));
- Assert::That( e1, Equals(1.435));
- Assert::That( f1, Equals(1.43));
- }
- };