繁体   English   中英

C ++比较表达式错误

[英]C++ comparison expression bug

这段代码有问题,但是我找不到引起它的原因。

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::npos ,其类型为std::string::size_type ,定义为实现定义的无符号整数。 无符号整数从不小于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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM