1

According to this question Unable to print the value of nullptr on screen

I can't print the value of a nullptr since it's of type nullptr_t, and std::cout has no such overload.

But, if you look at this:

int* f()
{
    return nullptr;
}

int main()
{
    std::cout << f();
}

The output is:

00000000

In this question Why does std::cout output disappear completely after NULL is sent to it they talk about a different problem.

I just want to understand why the std::cout can't print nullptr, but it actually can when nullptr is instead returned by a function.

Community
  • 1
  • 1
gedamial
  • 1,498
  • 1
  • 15
  • 30
  • 3
    Possible duplicate of [Why does std::cout output disappear completely after NULL is sent to it](http://stackoverflow.com/questions/7019454/why-does-stdcout-output-disappear-completely-after-null-is-sent-to-it) – sjsam Jul 16 '16 at 10:20
  • It's because of this `int* f()` – DimChtz Jul 16 '16 at 10:21
  • `std::cout` definitely has an overload for `int*`, which your function returns, which explains why you successfully get printed output. – linguamachina Jul 16 '16 at 10:23

2 Answers2

5

The reason for this is that nullptr is convertible to any pointer type (which is "printable"), but it is not itself a pointer.

Have a look at What exactly is nullptr?

Community
  • 1
  • 1
Johan Lundberg
  • 26,184
  • 12
  • 71
  • 97
2

Here is the meaning of nullptr from the CPP Standards [4.10]

  • A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type. Such a conversion is called a null pointer conversion.

Something the CPP Standards specifies, is that it isn't a std::nullptr_t value, it evaluates to zero or a prvalue of type std::nullptr_t.

In your case, it's pretty much is an (TYPE) pointer to some extent, so when you try to paste it out, it pastes out it's type's value (Where it points to, but by itself it won't). Your function returns an int*, and you give it a nullptr. So what you are basically doing is giving an int* a value. nullptr by itself won't have a value but

int* abc = nullptr;

will.

Noam Rodrik
  • 552
  • 2
  • 16
  • "it pretty much is an int pointer to some extent". Absolutely not. And it's not a pointer. – Johan Lundberg Jul 16 '16 at 10:51
  • Yeah, the answer was edited to "In your case", so now I don't need to add the "Int pointer" case (According to the question, not to the object itself) – Noam Rodrik Jul 16 '16 at 10:53