Monday 19 January 2015

Swap numbers in a single statement

This post demonstrates how to swap numbers in a single statement without using a temporary variable.

For your reference, representing all the forms of how to swap numbers without using a temporary variable.


Using addition and subtraction operators -


int main()
{
 int a,b;

 a = 10;
 b = 9;

 a = b-a;
 b = b-a;
 a = a+b;

 return 0;
}
 


Using XOR operator -


int main()
{
 int a,b;

 a = 10;
 b = 9;

 a = a^b;
 b = a^b;
 a = a^b;

 return 0;
}
 


In a single line -


int main()
{
 int a,b;

 a = 10;
 b = 9;

 a = (a+b) - (b=a);

 return 0;
}

 The above code throws the following warning if you are using any IDEs like codeblocks etc. Ignore the warning, the code just works fine.
warning: operation on 'b' may be undefined [-Wsequence-point]

Please share your thoughts on this post in the comments section.

Karthik Byggari

Author & Editor

Computer Science graduate, Techie, Founder of logicallyproven, Love to Share and Read About pprogramming related things.

4 comments:

 
biz.