Sunday, May 30, 2010

C++ basic interview questions

1) How do you swap two integers? Without another variable?

Answer:

   example main.cpp

   void main()
   {
      int a=2, b=3;
      swap (a, b);
   }


    swap ( int &a, int &b)   // pass by reference
   {
    int tmp = a;
   a = b;
   b = tmp;
  }

   Without a third variable
   swap ( int &a, int &b)
  {
       a = a +b;   // a = 2 +3 =5
       b = a-b;    // b = 5-3 =2
       a = a -b;   // a = 5 - 2 = 3, a and b swap
   }

  template < class T>
  void swap ( T &a, T &b)
  {
                     T tmp =a;
                     a = b;
                     b = tmp;
  }
  use swap (a, b ) to call the swap. It can swap any data type.

1 comment:

Search This Blog