2010-04-08

C++ riddle 2010-03-19 (solution)

This is the solution of the last blog.

Notice: You need C++ language knowledge to read this article.

First, I checked up that what does the string's default constructor do. But, it constructs a empty string instead of '1'.

Next, I put break points at all the constructors from my debugger. But, I cannot hit any breakpoint.

If I changed the middle()'s line as following,

std::string prefix("->"), middle(""), postfix("<-");

I got the expected result:

Hi:-><-


A hint is that the middle() is like this.

std::string middle();

Can you see now?

So what kind of C++ pitfall I jumped in?

1. This is not a definition of the string object middle, but, it is a declaration of a function middle that returns string.

2. Therefore, middle in the cout like is a function pointer.

3. When a function is declared, there should be a valid function pointer regardless the implementation. (Otherwise, linker failed and we can not have an executable.)

4. This pointer is implicitly converted to boolean type in this case.But, usually pointer will be printed out as hex number.

5. (C++ has no 'real' boolean, it is int.) Non NULL pointer implicitly becomes true.

6. (C++ has no 'real' boolean, it is int.) When true is outputted to the console out, it becomes 1.

This one line has this many pitfalls. Programming with C++ is hard.

Acknowledgements

Thanks to Peter of this nice C++ riddle.

No comments: