5

In the following code I have used cout<<(char*)NULL; after this line, my program printing nothing to the output screen. Does it mean I have done close(1) with cout here? What is actually happening here? Is this a bug? Please share your thoughts.

#include<iostream>
using namespace std;

void f(){
    cout<<"\nfun\n";
}

main(){
cout<<(char*)NULL;
f(); //not getting printed !
cout<<"\nhello\n";  //not getting printed !
cout<<"hii how are you?"; //not getting printed, why??
}

I have tried this with both gcc and DevCpp compilers, same behavior observed.

Renuka
  • 217
  • 1
  • 6

3 Answers3

5

cout << (char *)NULL causes undefined behaviour. Anything could happen. (The compiler assumes you don't do this when it generates assembly code).

A char * argument used here must point to a character in a null-terminated string.

M.M
  • 138,810
  • 21
  • 208
  • 365
3

Here you sets the badbit on the stream which causes nothing to be printed after cout<<(char*)NULL;

if (!__s)
 __out.setstate(ios_base::badbit);

The standard says: requires: shall not be a null pointer. So your program definitely has the undefined behavior and it should be fixed. You can clear the bad bit by using cout.clear().

In your case, cout<<(char*)NULL; causes undefined behavior. But GCC plays it safely.

Hope this helps!

uss
  • 1,271
  • 1
  • 13
  • 29
2

(char*)NULL doesn't turn NULL into a string like "NULL" if that's what you thought. NULL is actually a macro which expands to 0. Casting it to char* turns it into a pointer to zero (a null pointer). The only problem comes with printing it out. It is Undefined Behavior to try to print a null-pointer. Up to this point you cannot make sense of any behavior your program exhibits. The fact that your program didn't crash is a surprise to me.

David G
  • 94,763
  • 41
  • 167
  • 253
  • Yes, It was surprising and I ran this sample program on my Linux (using both compiler gcc and clang) and it did not crash. – Mantosh Kumar Apr 25 '14 at 03:07