C++ programming riddle, fun with function pointers

c++, function-pointers

Solution

A function pointer will be converted to `bool` when using with `cout`.

Why the function pointer is not converted to a `void *` implicitly, which is what operator << overloads on? because function pointers are not object pointers.

C++11 §4.10/2:

A prvalue of type “pointer to cv T,” where T is an object type, can be converted to a prvalue of type “pointer to cv void”. The result of converting a “pointer to cv T” to a “pointer to cv void” points to the start of the storage location where the object of type T resides, as if the object is a most derived object (1.8) of type T (that is, not a base class subobject). The null pointer value is converted to the null pointer value of the destination type.

Problem

Given the following code snippet: ``` #include <string> #include <iostream> int main() { std::string prefix("->"), middle(), suffix("<-"); std::cout << "Test: " << prefix << middle << suffix << std::endl; return 0; } ``` The advanced C++ programmer will immediately see that `middle()` is not calling `std::string`'s default ctor, instead it's a function declaration. What's interesting though: Why does gcc produce the following output: ``` Test: ->1<- ``` in contrast to Visual Studio's linker error? Does anybody know what's going on here?

Original source

Related problems