2

Can std::cout print "NULL" instead of 0 when printing a null pointer?? I can write a simple if statement like

if(pointer == nullptr)
  std::cout << "NULL";

But can I get the same result without using an if statement?

Philip Nelson
  • 1,027
  • 12
  • 28
Kaepxer
  • 319
  • 3
  • 16

3 Answers3

5

You can't really escape using an if statement, but you can make it into a one-liner with the ternary operator: (p == NULL ? std::cout << "NULL" : std::cout << p);

#include <iostream>

int main() {
  void *p = NULL;
  (p == NULL ? std::cout << "NULL" : std::cout << p);
  std::cout << std::endl;

  p = new int;
  (p == NULL ? std::cout << "NULL" : std::cout << p);
  std::cout << std::endl;
}

Demo

Nick Reed
  • 4,989
  • 4
  • 17
  • 37
4

You could make use of the ternary operator, ?.

pointer ? std::cout << pointer : std::cout << "NULL";

or with the gnu c++ compiler extension IF your pointer is a char*

std::cout << (pointer ?: "NULL");

granted that the second way will not work on all compilers because it is not officially part of the language.

I do not believe that there is an equivalent to std::boolalpha for pointers.

[EDIT]

As pointed out by @seleciii44, in the stack overflow post here, you can write your own overloaded stream insertion operator

std::ostream & operator<<(std::ostream &s, std::nullptr_t)
{
    return s << "nullptr";
}
Philip Nelson
  • 1,027
  • 12
  • 28
3

I can think of 2 ways.

1) The clear way: use ternary operator (?:)

    cout<<((ptr)?"":"NULL\n");

2) The nasty way, if you really don't want to use any conditional statements.

    cout<<&("NULL"[4*(!!ptr)]);

Why it works ?

!!ptr will set the value of ptr to 0 or 1 based on its value.

If it is null cout will see the char* starting from 0 index and will print "NULL", otherwise it will see it from index 4 and will print the terminating char.

This a very bad way as nullptr may be implementation defined and may be not portable.

Mostafa
  • 468
  • 3
  • 16
  • 1
    Technically, it doesn't print the terminating char. The terminating `\0` ends the loop, so no characters are printed. Should be very portable, as all the operations are well defined. But may be confusing, so deserves a comment if used in production code. – Eljay Oct 29 '19 at 19:07
  • 1
    Could do it as `cout << &"\0NULL"<:!ptr:>;` to shock your coworkers. – Eljay Oct 29 '19 at 19:16
  • Only problem is that it won't print the pointer if it is valid... Clever idea nonetheless – Philip Nelson Oct 29 '19 at 20:07