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::size_type
的 std::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
。
相关文章:
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 错误:表达式必须是可修改的 I值
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 错误:表达式不能用作函数
- C++/错误:表达式必须具有整数或无作用域枚举类型
- 错误表达式必须是插入函数(二叉树 C++)中的可修改 Ivalue
- 合并排序错误 - 表达式必须具有常量值
- 数组声明中的错误:表达式必须具有常量值
- 错误:表达式列表在初始化器[-fpermissive] Double Paycalc(p,yir,y)中被视为复合表达式
- 错误:表达式不能用作函数
- 我该如何解决此错误:表达式必须具有恒定值.环境是2013年
- 错误:表达式必须是可修改的LVALUE
- 错误:表达式必须具有指向类C++的指针
- 错误:表达式不能用作函数
- 错误:表达式必须具有积分或未引人注目的枚举类型
- 参数化sc_lv时报告错误(表达式必须具有常量值)
- 无法使用函数变量?错误表达式必须具有类类型
- 错误:表达式必须具有类类型
- 错误:表达式不能用作函数.如何删除它
- C++ - 错误:表达式必须具有指向对象的指针类型