Search code examples
c++nullptr

Why isn't working null pointer check for C style string?


This is my function:


void printCString(char *s)
{
    while (s != nullptr) // printing doesn't stop after ! from passed string.
    {
        std::cout << *s;
        ++s;
    }
}

and I call it:

char s[]{ "Hello, world!" };
printCString(s);

If I replace stop condition from while block with:

while (*s != '\0')

than it's working well. Can anybody explain me why this behavior?


Solution

  • s is never nullptr, since nullptr is unattainable via pointer arithmetic.

    Conceptually you'd need to deference s, but *s != nullptr will not compile. That's no bad thing since there is no guarantee that nullptr is the same as the C-style string terminator NUL.