Machine-translated by Google. Questions are authored in English.
Top

Discussion

If s and b are integers then  purpose of the following program fragment is to 

b = s + b ;

s = b - s ;

b = b - s ;

  • A.transfer the contents of s to b
  • B.transfer the content of b to s
  • C.exchange (swap) the contents of s and b 
  • D.negate the contents of s and b

Answer: C

Correct answer: exchange (swap) the contents of s and b

Trace the three assignments with initial values \( s \) and \( b \):

\[ b \leftarrow s+b, \qquad s \leftarrow (s+b)-s = b, \qquad b \leftarrow (s+b)-b = s \]

so the two values are exchanged without a temporary. The technique is a curiosity rather than good practice: the intermediate sum can overflow, and a compiler produces better code from an ordinary swap using a temporary variable.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.