C# Triple XOR: swapping two variables without a temporary variable

Swapping two variable values without using a temporary variable can be accomplished by using a triple XOR.

This is a little hack or trick that was used in the past but which is a bit obsolete now. The compiler is normally smart enough to optimize your temporary variable code.

Note that this code can give you bad results (might give you different result when using i.e. floats)

using System;

namespace ConsoleApplication1
{
 class Program
 {
   static void Main(string[] args)
   {
     Console.WriteLine(string.Format("Result: {0}", Class1.WriteReverse("The quick brown fox jumps over the lazy dog.")));
     Console.ReadLine();
   }
 }

 public class Class1
 {
   public static string WriteReverse(string s)
   {
     if (string.IsNullOrEmpty(s)) return "Not valid";

     char[] c = s.ToCharArray();
     int j = s.Length - 1;

     for (int i = 0; i < j; i++, j--)
     {
       c[i] ^= c[j];
       c[j] ^= c[i];
       c[i] ^= c[j];
     }

     return new string(c);
   }
 }
}

 

Note that I also used multiple statements in the for-loop. (see highlighted line)

Have fun! 😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s