1

I'm reading through Bjarne Stroustrup's A Tour of C++ and I'm having trouble understanding an early example. In the code below, a while loop is used to increment a pointer over a C style string until it hits the null character. What I don't get is why pointing to a null character would cause the pointer to take on the value of nullptr. It seems like it should be a perfectly good pointer that happens to point to a null value. I'd be surprised if it were an author error since the book is included in stackexchange's reccommendations here: The Definitive C++ Book Guide and List

int count_x(char∗ p, char x)
    // count the number of occurrences of x in p[]
    // p is assumed to point to a zero-terminated array of char (or to nothing)
{
    if (p==nullptr) return 0;
    int count = 0;
    for (; p!=nullptr; ++p)
        if (∗p==x)
            ++count;
        return count;
}
Community
  • 1
  • 1
agd
  • 99
  • 8
  • 4
    It wouldn't; that code sample is wrong – Ed S. Oct 07 '14 at 05:51
  • 1
    The sample in the book is different. The loop is `while(*p)`. Which edition do you have? – imreal Oct 07 '14 at 05:56
  • Well, I have a version that I found by googling "*A Tour of C++* pdf" (first result). Serves me right I guess, although interestingly it purports to be copywrited 2014. – agd Oct 07 '14 at 06:03
  • 1
    According to the [errata](http://www.stroustrup.com/Tour_printing2.html), "The code for count_if() is wrong", in the 1st printing, fixed in the 2nd. – Mike Seymour Oct 07 '14 at 06:06

2 Answers2

4

To check for null character, you should test *p != '\0', not p != nullptr.

timrau
  • 22,578
  • 4
  • 51
  • 64
2

It segs for the reasons you mention. Try:

  for (; *p; ++p)
Adrian May
  • 2,127
  • 15
  • 24