Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this code from Bjarne's "Tour of C++" valid?

If we pass an array to the function, we iterate through it until "p" is a nullptr. But this should never happen because the address after the last element that has value 0 in the array is not a nullptr(doesn't have value zero). How is this possible?

int count_x(char* p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-ter minated array of char (or to nothing)
{
  int count = 0;
  while (p) {
    if (*p==x)
      ++count;
    ++p;
  }
  return count;
}
like image 259
LearningMath Avatar asked Dec 24 '22 21:12

LearningMath


2 Answers

The code is wrong.

The while condition needs to be

while(*p)

instead of

while(p)

EDIT: Found it in the errata also - http://www.stroustrup.com/Tour_printing2.html

pp 11-12: The code for count_if() is wrong (doesn't do what it claims to), but the points made about the language are correct.

like image 43
user93353 Avatar answered Dec 28 '22 23:12

user93353


That function is not valid. Your version of the book contains an error. The correct version tests *p in the while condition.

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)
{
    int count = 0;
    while (*p) {
//         ^----------------- You omitted this asterisk.
        if (*p==x)
            ++count;
        ++p;
    }
    return count;
}

Update: the code apparently changed a little bit between printings, and the errata for the first printing mentions an error related to this function. Hat tip to @BenVoigt.

like image 134
rob mayoff Avatar answered Dec 28 '22 22:12

rob mayoff