Sunday, June 1, 2008

What does the expression 'a ^= b ^= a ^= b' do in C?

Question: What does the expression 'a ^= b ^= a ^= b' do in C?

Answer: It swaps the values of the two variables 'a' and 'b' without using a temporary variable, but only on few platforms and not everywhere. Whay is that so? Reason is very simple - this violates the concept of Sequence Point in C by attempting to modify a variable twice between two sequence points and hence the behavior is undefined and all the vendors are free to implement an undefined behavior the way they want. The funny thing is that this expression is not only platform dependent, but also value-dependent on those platforms. On the same platform, it may work for a set of values for 'a' and 'b', but may not for another set of values. You may like to check if it works on your platform :-)


No comments: