“C Tour的C ++”中的Buggy代码或不兼容的编译器? [英] Buggy code in "A Tour of C++" or non-compliant compiler?

查看:218
本文介绍了“C Tour的C ++”中的Buggy代码或不兼容的编译器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在第12页的C ++教程中看到了以下函数:

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;
}

while(p)听起来不对我。我认为应该是 while(* p)。但是,我不想过于假定,我用下面的代码测试函数。

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;
}

当我运行程序时,它退出与故障(内核转储)。我很高兴看到这个错误,因为代码看起来不对我开始。但是,现在好奇。是书中建议的代码不正确,还是编译器不是C ++ 11兼容?编译器是g ++(GCC)4.7.3。

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.

使得 count_x 的代码变得奇怪的是作者,Bjarne Stroustrup,在完成之前我写的一个实现之前开始。

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.

推荐答案

这是列在第二次打印C ++游戏的错误


Chapter 1:

第11-12页:count_if()的代码是错误的(不执行它要求的
),但是关于

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.

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

The code in the 2nd Printing now reads:

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;
}

C ++程序设计语言(第4版),它基于C ++之旅,但它没有这个bug。

There is a similar example in The C++ Programming Language (4th Edition) on which A Tour of C++ was based but it does not have this bug.

这篇关于“C Tour的C ++”中的Buggy代码或不兼容的编译器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆