使用按位和布尔值
Using bitwise & on boolean
本文关键字:布尔值 更新时间:2023-10-16
考虑以下代码片段:
main()
{
bool flag = true; //line 1
flag &= funcReturningBool(); //line 2
flag &= funcReturningBool2();
flag &= funcReturningBool3();
//....
//....
//....
//so many such cases
}
bool funcReturningBool()
{
bool ret = false;
// my logic which may (not) modify ret
return ret;
}
bool funcReturningBool2()
{
bool ret = false;
// my logic which may (not) modify ret
return ret;
}
bool funcReturningBool3()
{
bool ret = false;
// my logic which may (not) modify ret
return ret;
}
静态代码分析器工具指出以下问题(在第2行):
"逐位运算符正在应用于签名类型。结果值可能与预期值不符。"
有人能指出我是否做错了什么吗?还要规定一些有用的/合乎逻辑的替代方法来实现同样的目的!
您不应该在布尔值上使用逐位运算符。显然,编译器将funcReturningBool
或变量flag
的输出提升为带符号整数,并警告您可能出现的意外影响。
您应该坚持使用布尔运算符。如果&&=
存在,你就可以编写flag &&= funcReturningBool();
。相反,使用flag = flag && funcReturningBool();
相关文章:
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 变量定义到C++布尔值转换
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 重载更少,则运算符返回相反的布尔值
- 将此布尔值传递给此函数的最有效方法是什么?
- 如何设置 c++ 类的布尔值?
- 使用 MAKEWORD / MAKEWPARAM 使用布尔值而不是布尔值
- 将 10 个线程与原子布尔值同步
- 创建类似于布尔值的变量类型
- 布尔值向量的基于范围 for 循环
- 零点和布尔值之间的比较
- 简化对两个布尔值的 4 个 if/else 检查
- 无法创建带有布尔值和矢量的地图
- 对于完成布尔值设置为 true 后未停止的循环
- fstream / ifstream / ofstream 对象如何转换为布尔值
- C++:将值赋值给原始数据类型(例如布尔值)是原子操作吗?
- 为什么布尔值不能比作最后一点?
- 如何使用返回布尔值的函数?
- 将uintptr_t转换为布尔值会使 SSO 基准速度减慢数倍
- 布尔值始终评估为真