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?
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?
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;
}
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";
}
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.