Huh? I see no reason why cout
should fail simply because you executed
std::cout << 0 << std::endl;
It should output 0\n
. And it does. End of story.
(In case you're confused, please know that in C++, #define NULL (0)
.)
In case you wrote:
T* p = 0;
std::cout << p << std::endl;
then it will display the address 0
, (generally in hexadecimal and padded to the pointer size, since this is the preferred way of looking at pointers).
(This is btw the behavior you would get using the C definition of NULL, which is #define NULL ((void*)0)
.)
Only if you write
char* p = 0;
std::cout << p << std::endl;
are you in trouble. Now you're calling
template<class traits>
basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>& out, const char* s);
for which the Standard (section 27.7.3.6.4) says:
Requires: s
shall not be a null pointer.
When you do pass a null pointer, the rule 17.6.4.9 applies, which states that:
Each of the following applies to all arguments to functions defined in the C++ standard library, unless explicitly stated otherwise.
* If an argument to a function has an invalid value (such as a value outside the domain of the function or a pointer invalid for its intended use), the behavior is undefined.
So you're in the land of "undefined behavior". There's no guarantee that failbit
gets set and the program continues.
Please note that printf
behavior didn't actually depend on the type of NULL
. It's the format string "%s"
that caused treatment as a string (pointer to NUL-terminated character sequence).