Interview Question: Deciphering Code

Sample Question #266 (programming – C++)
 
What does the following C/C++ code do?
 
  x-=y=(x+=y)-y;
 
(Hint: break this down into separate statements)
Advertisements
This entry was posted in Sample Qs. Bookmark the permalink.

5 Responses to Interview Question: Deciphering Code

  1. Brett says:

    ANSWER
     

    x+=y;
    y=x-y;
    x-=y;
     
    This swaps the values of x and y, without using a temporary variable!
     
    (Comment: this kind of coding interpretation question is increasingly common at quant interviews)
     

  2. says:

    This is elegant!Happy Chinese new year Brett!

  3. Nathan says:

    It does whatever the compiler feels like, as this is undefined in C++. http://en.wikipedia.org/wiki/Sequence_point
     
    use std::swap(x, y); instead. it’s better anyways since you’ll get:
    a) well known case for compiler optimization — no code, just "renamed" registers/pointers. a nop.
    b) fewer pipeline stalls. 0 if the compiler can use (a). this = lower cpi = faster performance
    c) well defined behavior according to the C++ language specification :^)

  4. J says:

    All the best Brett, in lunar new year! Thanks for sharing and your book is really great! I have been reading it for long.

  5. Handong says:

    This type of code is typical bad code from programing point of view. 1. This code is so called "write-only" code. It adds difficulty to maintain and/or debug.2. What happens if x+y overflows?Like other poster has pointed out. It always better to call swap than writing code like this. The only advantage of this code bragging right.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s