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

为什么第二行的结果为假。有什么我没有看到的吗?

std::string::find 返回类型为 std::string::size_typestd::string::npos,定义为定义的无符号整数实现。无符号整数永远不会小于 0

您应该始终与std::string::npos进行比较,以检查std::string::find是否发现了某些东西。

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 int和一个int,所以提升规则适用,unsigned int被转换成一个int;正如我们之前看到的,npos的有符号等价物总是-1,所以这返回true

最新更新