C ++比较表达式bug

时间:2012-12-13 15:52:39

标签: c++

这段代码有问题,但我找不到导致它的原因。

bool Parser::validateName(std::string name) {
    int pos = name.find(INVALID_CHARS);               //pos is -1, 
    bool result = ((name.find(INVALID_CHARS)) < 0);   //result is false
    //That was weird, does that imply that -1 >= 0?, let's see
    result = (pos < 0)                                //result is true
    result = ((name.find(INVALID_CHARS)) == -1)       //result is true
    result = (-1 < 0)                                 //result is true
    ...
}

为什么第二行的结果为false。有没有我没见过的东西?

2 个答案:

答案 0 :(得分:9)

std::string::find返回类型为std::string::npos的{​​{1}},它被定义为实现定义的无符号整数。无符号整数决不会小于std::string::size_type

您应始终与0进行比较,以检查std::string::npos是否找到了某些内容。

答案 1 :(得分:2)

std::string::find在找不到请求的项目时返回std::string::npos。根据标准(§21.4/ 5):

static const size_type npos = -1;

但请注意string::size_type通常为unsigned int;这意味着-1被转换为其无符号等价物。通常为0xFFFF,这是unsigned int的最大值。

在你的第二行:

bool result = ((name.find(INVALID_CHARS)) < 0);

您正在比较两个unsigned int值(0xFFFF和0),因此返回false。另一方面,在你的第四行:

result = ((name.find(INVALID_CHARS)) == -1)

您有unsigned intint,因此适用促销规则,unsigned int转换为int;正如我们之前看到的,npos的签名等值总是-1,因此返回true