【发布时间】:2014-04-09 20:26:29
【问题描述】:
我在“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;
}
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;
}
当我运行程序时,它以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;
}
这让我在断定这是错误代码之前三思而后行。两个版本似乎都有问题。
【问题讨论】:
-
那段代码在我看来确实有问题。您是否有任何理由怀疑编译器不符合 C++11 标准? (另外,他们展示的代码绝对不是好的 C++ 代码——它应该使用
std::string和std::count算法~) -
@templatetypedef,我将很难将矛头指向 C++ 之父的书中的代码,并称其为 buggy,而没有确保有几次我不会失去理智:): )
-
@templatetypedef,该函数出现在本书的第一章“基础知识”中。他不会跳入
std::string和std::count是有道理的。