"A Tour of C++"中的错误代码或不兼容的编译器?

R S*_*ahu 15 c++ g++ c++11

我在"A Tour of C++"中看到了以下函数,第12页:

int count_x(char const* p, char x)
{
   int count = 0;
   while (p)
   {
      if (*p == x) ++count;
      ++p;
   }
   return count;
}
Run Code Online (Sandbox Code Playgroud)

这条线while (p)听起来不对我.我以为它应该是while (*p).但是,不想过于放肆,我用下面的代码测试了这个函数.

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;
}
Run Code Online (Sandbox Code Playgroud)

当我运行该程序时,它退出了Segmentation fault (core dumped).我很高兴看到这个错误,因为代码看起来不适合我开始.但是,现在很好奇.书中建议的代码是不正确的还是编译器不符合C++ 11?编译器是g ++(GCC)4.7.3.

令人感到count_x奇怪的是,作者Bjarne Stroustrup在完成我首先编写的实现之前,先从以下实现开始.

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;
}
Run Code Online (Sandbox Code Playgroud)

在结束这是错误的代码之前,它让我三思而后行.两个版本似乎都是错误的.

Chr*_*rew 5

这是在A Tour of C++的第二次印刷勘误表中列出的:

第1章:

第11-12页:count_if()的代码是错误的(没有按照它声称的那样做),但关于语言的要点是正确的.

第二次印刷中的代码现在为:

int count_x(char* p, char x)
    // count the number of occurences 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;
    while(*p) {
        if(*p==x)
            ++count;
        ++p;
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)

C++编程语言(第4版)中有一个类似的例子,其中A Tour of C++基于它,但它没有这个bug.