Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cpp, "\0" == NULL returns false? How to figure it is null ptr or not?

I am getting these results. What am I doing wrong?

const char *c = "\0";
cout << (c == NULL); // false
cout << (c == nullptr); //false

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

All literal strings in C++ are really constant arrays of characters, including the null-terminator character.

So doing e.g.

const char* c = "\0";

is somewhat equivalent to

char const internal_string_array[] = { '\0', '\0' };
const char* c = &internal_string_array[0];

So a pointer to a literal string will never be a null pointer.

Also there’s a difference between a null pointer and the string null terminator character. A null pointer is a pointer which have been initialized to point to nowhere. A string null terminator character is the character '\0'. These two are different things.


If you want to check to see if a C-style string (using pointers or arrays) is empty, then you first need to make sure it’s not a null-pointer (if you’re using pointers) and then check to see if the first character is the string null terminator character:

if (c == nullptr)
{
    // No string at all!
}
else if (c[0] == '\0')
{
    // String exists, but is empty
}
else
{
    // String exists, and is not empty
}

For std::string objects (which you should use for almost all your strings) then you don’t need the null-pointer check:

if (str.empty())
{
    // String is empty
}
else
{
    // String is not empty
}

Also note that even if a string is not empty, it might contain unprintable characters (like the ASCII control characters), or characters that are "invisible" (like for example space or tab).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading