使用按位和布尔值

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();