0

I wonder about "cout" nullptr doesn't work. It work only once. But "printf" work on the main function.

#include <iostream>
int main() {
  const char *np=nullptr;

  std::cout << "np: "<<np<<std::endl;
  std::cout << "np: "<<np<<std::endl;
  std::cout << "np: "<<np<<std::endl;
  printf("printf np:%s\n",np);
  std::cout << "np: "<<np<<std::endl;
  std::cout << "np: "<<np<<std::endl;
}

It work like below.

np: printf np:(null)

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
  • 1
    @TonyTannous Probably not. Op is not trying to print the `nullptr` keyword, but a `const char*` that _is_ null. – Lukas-T Jun 12 '20 at 06:45
  • It is not about printing a nullptr, it is printing what the pointer is pointing on. If pointer is invalid, we have UB. – Klaus Jun 12 '20 at 06:49

2 Answers2

0

nullptr is a type of std::nullptr_t, which doesn't defines the any operators for std::cout to be able print objects of that type.

One possible way to print, it'll print zero although:

#include <iostream>

int main(void) {
    const char *np = nullptr;

    std::cout << static_cast<const void*>(np) << std::endl;

    return 0;
}

Just cast it to a const void pointer. Then you'll get something like:

0

But not (null), this is what was explained in the top.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
0

It's undefined behaviour

In both cases you are printing a C-style-string (a const char *). So the implementation needs to find the length of this string and searches the terminating null character in it. But the pointer is invalid, so you get undefined behaviour.

Technically both cases are UB, but the implementation of printf you are using seems to be recognizing the invalid pointer and prints (null) instead, whereas std::cout just crashes.

(Or maybe it also recognizes the invalid pointer and gracefully sets the fail bit, thus ignoring further operations. But ultimately it's UB, so anything can happen here.)

Lukas-T
  • 11,133
  • 3
  • 20
  • 30