简体   繁体   English

C ++比较表达式错误

[英]C++ comparison expression bug

There's something wrong with this code, but I can't find what's causing it. 这段代码有问题,但是我找不到引起它的原因。

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

Why is the result false at the second line. 为什么第二行的结果为假。 Is there something I'm not seeing? 有没有我看不到的东西吗?

std::string::find returns std::string::npos which is of type std::string::size_type which is defined to be an implementation defined unsigned integer. std::string::find返回std::string::npos ,其类型为std::string::size_type ,定义为实现定义的无符号整数。 Unsigned integers are never smaller than 0 . 无符号整数从不小于0

You should always compare against std::string::npos to check whether std::string::find found something or not. 您应该始终将其与std::string::npos进行比较,以检查std::string::find是否发现了某些东西。

std::string::find returns std::string::npos when it does not find the requested item. std::string::find在找不到所请求的项目时返回std::string::npos According to the Standard (§ 21.4/5): 根据标准(第21.4 / 5节):

static const size_type npos = -1;

But see that string::size_type is usually unsigned int ; 但是请注意, string::size_type通常是unsigned int this means that -1 is converted into its unsigned equivalent. 这意味着-1转换为它的无符号等效项。 Usually, 0xFFFF, which is the maximum value for unsigned int . 通常为0xFFFF,这是unsigned int的最大值。

In your second line: 在第二行:

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

you are comparing two unsigned int values (0xFFFF and 0), so this returns false . 您正在比较两个unsigned int值(0xFFFF和0),因此返回false On the other hand, in your fourth line: 另一方面,在您的第四行中:

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

you have an unsigned int and an int , so promotion rules apply and the unsigned int is converted into an int ; 您有一个unsigned int和一个int ,因此适用促销规则,并且unsigned int转换为int ; as we saw before, the signed equivalen of npos is always -1, so this returns true . 如我们之前所见, npos有符号等价始终为-1,因此返回true

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

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