I saw the following function in "A Tour of C++", page 12:
int count_x(char const* p, char x)
{
int count = 0;
while (p)
{
if (*p == x) ++count;
++p;
}
return count;
}
The line while (p)
did not sound right to me. I thought it should've been while (*p)
. However, not wanting to be too presumptuous, I tested the function with the following code.
int main(int argc, char** argv)
{
char* p = argv[1];
char x = argv[2][0];
int count = count_x(p, x);
std::cout
<< "Number of occurences of "
<< x << " in " << p << ": " << count << std::endl;
return 0;
}
When I ran the program, it exited with Segmentation fault (core dumped)
. 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.
What makes the code of count_x
strange is that the author, Bjarne Stroustrup, starts with the following implementation before finishing with the one I wrote first.
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;
}
It made me think twice before concluding this is buggy code. Both versions appear to be buggy.