Zhigang Wang
  • Home
  • Blog
  • Wiki
  • LDP
  • Planet

Exchange two values without a variable

Last modified on 2009-12-01

How to exchange two values without a variable? Here are some solutions:

void swap1(int& a,int& b)
{
	a^=b;
	b^=a;
	a^=b;
}

void swap2(int& a,int& b)
{
	a=a+b;
	b=a-b;
	a=a-b;
}

void swap3(int& a,int& b)
{
	a=a-b;
	b=a+b;
	a=b-a;
}

__asm{
    xchg val1,val2
}

# python
a, b = b, a
 

Categories

  • All contents
  • English contents
  • Chinese contents

Feeds

  • AtomAll contents
  • AtomEnglish contents
  • AtomChinese contents

Tags

  • gtd
  • syslog
  • twiki
  • virtualizaion
  • wiki
  • xen

Copyright © 2012 Zhigang Wang. Some right reserved.

The views expressed on this web site are my own and do not necessarily reflect the views of Oracle.