GATE / CS ARCHIVE

GATE CSE 1993 / QUESTION 7.4

Addition-subtraction swap

Compiler Design · Other / Mixed Topics · Full GATE CSE 1993 paper

GATE 1993, Q7.4 2 marks · MSQ
Report issue

Other / Mixed Topics

Question 7.4, GATE 1993: What do a:=a+b; b:=a−b; a:=a−b accomplish for initialized integer variables?
Tap to enlarge
Select all that apply
Answer & solution

Answer: A: exchange a and b, assuming no overflow (no official key was published)

Let the initial values be a0,b0. After the first statement a=a0+b0. The second computes b=(a0+b0)−b0=a0. The final statement gives a=(a0+b0)−a0=b0, completing the swap without a separate temporary. This derivation assumes the intermediate sum is representable or a defined modular arithmetic model. The snippet declares variables but does not initialize them; as a standalone program it would not define starting values. Its intended transformation concerns values supplied before this segment.

Original paper, page 7