Jump to content

Swapping array bytes


bill
 Share

Recommended Posts

There's always this classic algorithm for swapping variables without a temporary variable:

x = x ^ y;
y = x ^ y;
x = x ^ y;

( ^ is the xor operator)

It works as long as x and y are not the same variable (ie, not the same address)

Link to comment
Share on other sites

hi bill

i suppose that flukes solution might work, but it would be harder for you to read (and understand) later on.

i would stay with the temporary variable, but you would limit the context by enclosing within braces {}

int x,y;

...

{

  int tmp;

  tmp = x;

  x = 7;

  y = tmp;

}

this way the compiler has the option of what to do with the tmp variable, it may only use it in that part of code, or it may initialise it at the beginning of the function.  as i said, its the compilers choice.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

×
×
  • Create New...