Faced with incomprehensible behavior.

There is a code in Maine:

char* pC = NULL; std::cout << pC; std::cout << "Any output"; 

And that is not clear, it displays nothing. All output following the pC output (char * type pointer pointing to NULL) is no longer output. Interestingly, if you use an int * type pointer, then everything works correctly.

Why so with char * = NULL? Sorry if the question is stupid for you.

    2 answers 2

    The same question in English SO

    STRICT EXPLANATION

    The output char* = nullptr with cout causes undefined behavior . This is a violation of the standard of language, and it is simply impossible to do.

    In the case of libstdc , this "Undefined Behavior" becomes quite definite, the events unfold like this:

    iostreams tries to interpret char* as a string. And when you bother him with zero, it spoils - puts itself a bit of error and stops working.

    A little experiment on ideone :

     #include <iostream> #include <cstdio> int main() { char* pC = nullptr; //использование nullptr //вместо NULL - использование //современного стандарта языка std::cout << pC; // выводим статус потока, будет "0" printf(" goodbit state is %d\n",\ std::cout.rdstate() == std::ios_base::goodbit); std::cout << "Any output"; // не сработает - cout сломан std::cout.clear(); //сбрасываем ошибку std::cout << "Any output"; //теперь вывод работает return 0; } 

    However, rely on it is not worth it. The correct solution is not to try to output nullptr .

    If you need to display the value of a pointer to a string, cast its type to something else.

      std::cout << static_cast<void*>(pC) << std::endl; 
    • one
      Thank you very much for your answer. Exhaustively. - Ligvest O

    Uncertain behavior happens here. Because in the description of the operator in English and white it is written :

    If it doesn’t point to a null terminated character sequence, it causes an undefined behavior.

    Obviously, the NULL pointer is not a "null terminated character sequence".