简体   繁体   中英

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. Unsigned integers are never smaller than 0 .

You should always compare against std::string::npos to check whether std::string::find found something or not.

std::string::find returns std::string::npos when it does not find the requested item. According to the Standard (§ 21.4/5):

static const size_type npos = -1;

But see that string::size_type is usually unsigned int ; this means that -1 is converted into its unsigned equivalent. Usually, 0xFFFF, which is the maximum value for 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 . 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 ; as we saw before, the signed equivalen of npos is always -1, so this returns true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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