0

If I write this code:

const char * b = NULL;
std::cout << "Hello!" << b;

I get this output:

Hello!

However, if I change the order to:

const char * b = NULL;
std::cout << b << "Hello!";

I get no output whatsoever, so I'm curious about it.

I can guess that probably the << operator for cout reads until a NULL, so everything after it is ignored, but wonder if someone could give me some more insight about it.

user2891462
  • 3,033
  • 2
  • 32
  • 60
  • Possible duplicate of: [Is printing a null-pointer Undefined Behavior?](http://stackoverflow.com/questions/23283772/is-printing-a-null-pointer-undefined-behavior) – David G Dec 05 '14 at 15:32

1 Answers1

4

The operator has a precondition:

Requires: s shall not be a null pointer.

By breaking this precondition, you cause undefined behaviour. Anything could happen.

(As mentioned in the comments, one popular implementation sets failbit and badbit in this case, which would explain the behaviour you see. But that's not something you can rely on.)

David G
  • 94,763
  • 41
  • 167
  • 253
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644