Why does cout print “2 + 3 = 15” in this snippet of code?

后端 未结 5 780
暗喜
暗喜 2020-12-07 16:15

Why is the output of the below program what it is?

#include 
using namespace std;

int main(){

    cout << \"2+3 = \" <<
    cou         


        
5条回答
  •  执念已碎
    2020-12-07 17:01

    As Igor says, you get this with a C++11 library, where std::basic_ios has the operator bool instead of the operator void*, but somehow isn't declared (or treated as) explicit. See here for the correct declaration.

    For example, a conforming C++11 compiler will give the same result with

    #include 
    using namespace std;
    
    int main() {
        cout << "2+3 = " << 
        static_cast(cout) << 2 + 3 << endl;
    }
    

    but in your case, the static_cast is being (wrongly) allowed as an implicit conversion.


    Edit: Since this isn't usual or expected behaviour, it might be useful to know your platform, compiler version, etc.


    Edit 2: For reference, the code would usually be written either as

        cout << "2+3 = "
             << 2 + 3 << endl;
    

    or as

        cout << "2+3 = ";
        cout << 2 + 3 << endl;
    

    and it's mixing the two styles together that exposed the bug.

提交回复
热议问题