[英]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.