Is printing a null-pointer Undefined Behavior?

后端 未结 2 957
旧巷少年郎
旧巷少年郎 2021-01-06 00:44

When studying the sample code for this question I had assumed it was Undefined Behaviour which was preventing subsequent uses of std::cout from printing. But it

2条回答
  •  误落风尘
    2021-01-06 01:34

    basic_ostream's operator<<(basic_ostream<>&, const char*) function requires that the char* is non-null - it is designed to print the string the pointer points to. So it is undefined behavior to send a null char* to cout. (See C++11 27.7.3.6.4/3 "Character inserter function templates").

    However, basic_ostream's operator<<(basic_ostream<>&, const void*) function simply prints the value of the pointer, so a null pointer will work properly with that overload.

提交回复
热议问题