What is the reason why C ++ std IO doesn't output NULL gracefully?
Possible duplicate:
Why does std :: cout output disappear completely after sending NULL
It seems if you try:
std::cout << NULL << endl;
std::cout << "hell" << endl;
it doesn't print anything and C ++ IO stops working for all subsequent outputs.
but it works fine in C stdio:
printf("%s\n", NULL);
printf("%s\n", "hell");
(zero)
hell
Is there a good reason why C ++ IO cannot do the same?
(edited in response to comments) well to be clear, NULL has a type, say const char *
const char* getxxx(); // may return NULL,
cout << getxxx(); // won't work if NULL returned
AND? I see no reason why there cout
should be a failure simply because you followed
std::cout << 0 << std::endl;
He should get out 0\n
. And he does . End of the story.
(If you are confused, find out that in C ++,. #define NULL (0)
)
If you wrote:
T* p = 0;
std::cout << p << std::endl;
then it will display the address 0
(usually in hex and padded with the pointer size, as this is the preferred way to look up pointers).
(It depends on the behavior you get using the C NULL definition, which is #define NULL ((void*)0)
.)
Only if you write
char* p = 0;
std::cout << p << std::endl;
You have problems. Now you call
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:
Required: Must
s
not be a null pointer.
When you pass a null pointer, rule 17.6.4.9 applies, which says that:
Each of the following statements applies to all arguments to functions defined in the C ++ Standard Library, unless explicitly stated otherwise. * If a function argument has an invalid value (for example, a value outside the domain of the function, or the pointer is not valid for its intended use), the behavior is undefined.
So you are in a country of "undefined behavior". There is no guarantee that it failbit
will be installed and the program will continue.
Note that the behavior is printf
actually type independent NULL
. It is the format string "%s"
that invoked the call as a string (pointer to a NUL character sequence).
source to share