“A Tour of C++"中的错误代码还是不兼容的编译器?
我在A Tour of C++"第 12 页看到了以下函数:
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;
}
当我运行程序时,它以 Segmentation fault (core dumped)
退出.我很高兴看到这个错误,因为代码在我看来并不合适.不过,现在很好奇.是书中建议的代码不正确还是编译器不兼容 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.
推荐答案
这在 第二次勘误表中列出A Tour of C++的打印:
第 1 章:
pp 11-12: count_if() 的代码是错误的(没有按照它声称的那样做to),但关于语言的观点是正确的.
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 版) 中有一个类似的示例,A Tour of C++ 是基于的,但它没有这个错误.
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.
相关文章