swapping program does not use third variable

Answer Posted / rajeshwar raja

Swap(int* a, int* b)
{
(*a) ^= (*b) ^= (*a) ^= (*b);
}

Explanation:
Expressions are evaluated from right to left.
Take the right most operation (*a) ^= (*b), its is short
hand XOR operation between 'a' and 'b'.
Assume a = 2 and b = 3.
a = 2 ^ 3 = 1
Next operation (*b) ^= (*a),
b = 3 ^ 1 = 2 (Note a is 1 now) ***(b is 2)***
Next operation (*a) ^= (*b)
a = 1 ^ 2 = 3 (Note b is 2 now) ***(a is 3)***

SWAPPED!!!
It can swap complex data structures also.

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Why do we use class?

635


Can you inherit a private class?

633


What is the real time example of encapsulation?

599


Why do pointers exist?

663


What is a function in oop?

633






There are two base class B1,B2 and there is one class D which is derived from both classes, Explain the flow of calling constructors and destructors when an object of derived class is instantiated.

1458


Which language is pure oop?

551


INSTANCE FIELDS DECLARED private ARE ACCESSIBLE BY THE METHODS ONLY.CAN WE CHANGE THE private FIELD OF AN OBJECT IN A METHOD OF SOME OTHER OBJECT OF THE SAME CLASS?

1637


What is the real time example of inheritance?

643


Write a C++ program without using any loop (if, for, while etc) to print prime numbers from 1 to 100 and 100 to 1 (Do not use 200 print statements!!!)

1639


write a code for this:trailer recordId contains a value other than 99, then the file must error with the reason ‘Invalid RECORD_ID’(User Defined Exception).

1642


write a program to enter a string like"sunil is a good boy and seeking for a job" not more than 10 characters including space in one line,rest characters should b in other line.if the next line starts from in between the previous word,then print whole word to next line.

1795


What is difference between oop and pop?

618


What is Difference Between Inheritance and creating object and getting data? means Class A extends B{ B.getMethod();} (OR) Class A{ b obj=new B(); obj.getMethod(); }

1989


What is the diamond problem in inheritance?

579