Looking at how to use the bitwise operators, I ran across the following technique for swapping two values, which I think should work for any primitive data type (as long as a and b have distinct memory locations), and which doesn't require creating an extra variable:
Isn't this technique invariably faster (in addition to conserving a little memory, which presumably doesn't really matter) than the normal technique of using a temporary variable?Code:/* code that determines (primitive) datatypes of a and b and assigns values */ a ^= b; // now a has a bit set only in those spots where 1 of a and b had a bit set b ^= a; // now b is set to the value of the original a a ^= b; // now a is set to the value of the original b



LinkBack URL
About LinkBacks


