title: Buggy code in "A Tour of C++" or non-compliant compiler?
body: <p>I saw the following function in "A Tour of C++", page 12:</p>
  
  <pre><code>int count_x(char const* p, char x)
  {
     int count = 0;
     while (p)
     {
        if (*p == x) ++count;
        ++p;
     }
     return count;
  }
  </code></pre>
  
  <p>The line <code>while (p)</code> did not sound right to me. I thought it should've been <code>while (*p)</code>. However, not wanting to be too presumptuous, I tested the function with the following code.</p>
  
  <pre><code>int main(int argc, char** argv)
  {
     char* p = argv[1];
     char x = argv[2][0];
     int count = count_x(p, x);
  
     std::cout
        &lt;&lt; "Number of occurences of "
        &lt;&lt; x &lt;&lt; " in " &lt;&lt; p &lt;&lt; ": " &lt;&lt; count &lt;&lt; std::endl;
     return 0;
  }
  </code></pre>
  
  <p>When I ran the program, it exited with <code>Segmentation fault (core dumped)</code>. I was glad to see that error since the code did not look right to me to start with. However, now am curious. Is the code suggested in the book incorrect or is the compiler not C++11 compliant? The compiler is g++ (GCC) 4.7.3.</p>
  
  <p>What makes the code of <code>count_x</code> strange is that the author, Bjarne Stroustrup, starts with the following implementation before finishing with the one I wrote first.</p>
  
  <pre><code>int count_x(char const* p, char x)
  {
     if(p==nullptr) return 0;
     int count = 0;
     for (; p!=nullptr; ++p)
     {
        if (*p == x)
           ++count;
     }
     return count;
  }
  </code></pre>
  
  <p>It made me think twice before concluding this is buggy code. Both versions appear to be buggy.</p>