Amusing C++

Lisa Simpson gave three apples to her brother Bart, then took back one.
Q.: How many apples does Bart have?
A.: Who knows? We're still unaware of how many apples he had to start!

Can C++ be funny? Let's check it out! Here are some examples that gladden the programmer's eye. Enjoy looking at them!

Let us start - and may the Source be with you! Suppose we have the following code:

int a = 5;
int b = a++ + ++a;

What does b equal? Are you sure? :) The point is that the right value lies somewhere between 10 and 14! My GCC returns 12, but that's not the limit yet! The C++ Standard does not presuppose the calculation of the ++ operator before the assignment operator is done - so that the answer may vary depending on the compiler; it may even depend on the optimization keys. Note that the result of the operation i = i++ is not defined either! People who want to learn more, can google "C++ sequence point", while we go on!

What do you think - is this code workable?

int i[i];
int j = j;
x x;
int y::y = x.x;

Strange as it may seem, it is - if we do like this:

const int i = 1;
const int j = 2;
struct x
{
   int x;
};
namespace y
{
   int i[i];
   int j = j;
   x x;
   int y::y = x.x;
};

Visibility overlap did its dirty deed! :) However, MSVC does not accept such code: it considers the declaration of int x to be a declaration of the constructor (the latter, as is known, cannot return a value). And, what's even worse, the namespaced variable j will have an unexpected value, though it is "initialized". So, this clearly indicates that such "tricks" are not worth being played!

Let's go on with the next example. Here's another nice code I've gotten you into! :) This one marked the beginning of my collection of C++ pranks, and I like it the most. Apart from being a really cool prank, it also comprises a psychological trick. Just look at this:

T t1;
T t2(t1);
T t3 = t1;
T t4();

Which constructor will be called in each of these four cases? If you have decided that those must be:

  • default constructor,
  • copy constructor,
  • assignment operator, and
  • default constructor again,
then you are mistaken... twice! Of course, first comes the default constructor; second comes the copy one, which apparently follows from the syntax. But in the third case, in spite of the = sign, ye good olde copy constructor is activated; we create a new object, not initialize an existing one! The last case is not the creation of an object at all, it's... the declaration of a function! The latter does not take the parameters and returns the type T; compare:

int func();

If you made no mistakes, congratulations! If you made one nevertheless and are now craving another chance to win, here's a new opportunity for you! Suppose you have this class:

class C {
public:
    C()                    { printf("default\n"); }
    C(long)                { printf("long\n"); }
    explicit C(int)        { printf("int\n"); }
    C(const C&)            { printf("copy\n"); }
    C &operator=(const C&) { printf("op=\n"); return *this; }
};

Also, you have a code that involves it:

void prn(int n)
{
   cout << n << ": ";
}
int main()
{
   const int i = 0;
   prn(1); C c1();
   prn(2); C c2 = i;
   prn(3); C c3(i);
   prn(4); C c4 = C(i);
   prn(5); C c5 = (C) i;
   prn(6); C c6 = static_cast(i);
   return 0;
}

What will be displayed on the screen then? To be honest, I made a mistake myself here. And that mistake was severe and reiterated :) So, please be extremely focused. Done? The right answer is:

1: 2: long
3: int
4: int
5: int
6: int    

Naturally, one is blank; as you remember, it is a function declaration. Two did not manage to build a class from int, since the int-constructor is specified as explicit; however, the compiler obligingly converted int into long - where its own constructor already exists. The rest of options are variations on a theme of C(i), although differently decorated. I cannot but admire the competence of the translator, which used neither excessive copy constructor, nor assignment constructor, nor even default constructor. C++ at its best!

Here's the last example - maybe the most "practical" among those cited. Suppose you need to create a cycle in which the value of a variable tends to zero. Certainly, you can use the operator for. But we can also do like this!

int i = 10;
while (i --> 0)
{
   cout << i << endl;
}

This thingamajig is called "arrow operator", just in case.

Here were the tricks originating in our more-than-native language. And then, C++0x may well come, which conceals many such pranks, I guess. As for now, let's keep in mind that this code is nothing but a joke - it ain't a blueprint for action! :)

Table of authorities

  • C++ Standard
  • Herb Sutter, Exceptional C++ (Addison-Wesley, 2000, ISBN 0-201-61562-2)
  • Internet surfing


About the Author

Vasily Starostin

I am C++ developer who also writes articles and books (tech & psychology).

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: April 22, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Database professionals — whether developers or DBAs — can often save valuable time by learning to get the most from their new or existing productivity tools. Whether you're responsible for managing database projects, performing database health checks and reporting, analyzing code, or measuring software engineering metrics, it's likely you're not taking advantage of some of the lesser-known features of Toad from Dell. Attend this live …

  • Live Event Date: May 6, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT While you likely have very good reasons for remaining on WinXP after end of support -- an estimated 20-30% of worldwide devices still are -- the bottom line is your security risk is now significant. In the absence of security patches, attackers will certainly turn their attention to this new opportunity. Join Lumension Vice President Paul Zimski in this one-hour webcast to discuss risk and, more importantly, 5 pragmatic risk mitigation techniques …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds