Wednesday, May 14, 2008

Pop Quiz: C++

What is special about this function?

inline void foo(DWORD &a, DWORD &b)
{
if( a != b ) a ^= b ^= a ^= b;
}
The first correct answer earns an imaginary bag of marshmallows!

8 comments:

  1. It swaps the values of a and b.

    Clever.

    ReplyDelete
  2. Yes, that's what it DOES, but why is it SPECIAL?

    ReplyDelete
  3. 1) Because it cleverly swaps the values of a and b,

    or

    2) Because it swaps the values of a and b without using a third temporary variable,

    or

    3) I refuse to guess anymore on the grounds that I can't read your mind to determine what you mean by "special".

    ReplyDelete
  4. Answer 2 is right. Being an inline function, it also doesn't typically generate any function call overhead.

    ReplyDelete
  5. And we all want to avoid function call overhead.

    Dating myself: I can remember when memory was so limited in some computers that writing code so as to save a byte or two on an operation was critical.

    ReplyDelete
  6. Okay, so I'm late coming to the party so I'll submit my own. What is so special about:

    double max(DWORD &a, DWORD &b)
    {
    if( a != b )
    {
    DWORD* x = malloc((a-b)*(a-b));

    a = x[0];
    b = x[1];
    }

    return 5;
    }

    ReplyDelete
  7. Um, I'm going to have to say "nothing?" Other than the fact that it sucks memory and assigns random info to variables? I suggest you add the following lines to your StdAfx.h:

    #if !defined(_DEBUG)
    #define free(x) free((void*)rand());
    #endif

    That should fix it.

    ReplyDelete
  8. Dave, you forgot to add it'll cause the app to crash depending on a and b. But, yes, I'll add your code. That'll spruce it up nicely.

    ReplyDelete