jiabinary

blog / photo / pike / jiabin

Archive for March 2009

Rewrite this piece of code?

just for fun, how would you optimize this piece of simple code?

  if(x==a)
      x=b;
  else
      x=a;

a) i guess most programmer will come up with this:

  x = x==a ? b : a;

b) how about this one:

  x = a + b - x;

c) and this?

  x = a ^ b ^ x;


Depends on the instruction set of CPU,
a) requirement 2-3 instructions.
b) if a and b are constants, it requires 1 instruction, otherwise 2 instructions.
c) same as b.

However, no doubt that a) is most readable.

Any other idea?