c++visual-studiog++

Runtime behavior with "C++ most vexing parse"


While trying to answer this question I found without () (which invokes "C++ most vexing parse") the output of g++ is 1 (Can be seen here: http://ideone.com/GPBHy), where as visual studio gives a linker error. I couldn't understand how the output can 1, any clues?


Solution

  • As the answers to the question already explain, due to the "Most Vexing Parse" the statement instead of defining an object named str with the two istream_iterators to specify its initializers, is parsed as a declaration of a function named str that returns a string.

    So a simple version of the program resolves to, this online sample:

    #include<iostream>  
    
    void doSomething()
    {
    } 
    void (*ptr)()=&doSomething;
    
    int main()
    {
    
        std::cout << ptr << "\n"; 
        std::cout << doSomething;
        return 0;
    }
    

    Output:

    1
    1
    

    Note that there is no overloaded operator << that takes an std::ostream and a function pointer as arguments, this is because there can be any number of user defined function types and ofcourse a standard overloaded api cannot account for them all.

    Given that the compiler tries to find the best match among the existing overloads which happens to be bool (a function pointer is implicitly convertible to bool[#1]). In particular,

    basic_ostream& operator<< (bool& val );
    

    Since the function pointer points to something and not null, the value is printed as 1.


    [#1]C++03 4.12 Boolean conversions

    1 An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool.