1

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?

4
  • 1
    Where are you stuck exactly? While traversing a C-style string you'll eventually find a zero character, but the pointer you use for traversal has no reason to become null. Commented Dec 16, 2019 at 9:46
  • 1
    s points somewhere in memory. You are checking whether s points to memory location zero (more or less). There's no reason why the next memory location after the ! of the string should be memory location zero. Commented Dec 16, 2019 at 9:48
  • 1
    You basically expect s to point to nullptr when you reach the 15th iteration, but you don't know what's in there (undefined) because this memory is not part of s. Commented Dec 16, 2019 at 9:50
  • 1
    I got it now. I mixed nullptr for null character. Commented Dec 16, 2019 at 9:53

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

12 Comments

*s != nullptr shouldn't compile.
@n.'pronouns'm.: Indeed (although I did once use a compiler that allowed it ;-) )
@olivecoder: No, that's undefined behaviour. Pointer arithmetic is only valid within arrays.
@olivecoder: Yup, I use one that allows it too. But on other occasions a compiler might optimise away the loop, or eat your cat.
@olivecoder No, nullptr is not attainable via pointer arithmetic. That gcc compiles your code (which has undefined behavior) to return 0; is absolutely not proof of your theory - you can't prove that a program is valid/UB-free by showing how a compiler accepts it. And for the record, clang will turn it into an endless loop (which, btw, is also UB): godbolt.org/z/Rm5HEh How do you explain that?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.