When I use the following minimal code in an C++ console application in Visual Studio 2019, I get two warnings, which are completely opposite.
int main()
{
unsigned char op1 = 0x1;
unsigned char op2 = 0x3;
unsigned char result1 = op1 | op2;
unsigned char result2 = op1 || op2;
}
The warning at unsigned char result1 = op1 | op2;
is
lnt-logical-bitwise-mismatch Using bitwise '|' when logical '||' was probably intended.
The warning at unsigned char result2 = op1 || op2;
is
lnt-logical-bitwise-mismatch Using logical '||' when bitwise '|' was probably intended.
This is a little bit curious.
My intention was to use the bitwise operator. How could I change the line unsigned char result1 = op1 | op2;
, so that the Visual Studio 2019 warning goes away?
The warning is not from the compiler; the output is error-free. Maybe it comes from the ReSharper C++ module or from Visual Studio code analysis.
(Of course I could ignore that warning, but in the original code there are a lot of them, because there a lot of unsigned char bitwise operations.)
char
type is very unusual for bitwise operations. Why are your variableschar
instead ofint
? – Enormousop1 || op2
should only be used with booleans andop1 | op2
should only be used with integers, not chars – Canticlechar
does triple duty in C++, whereasint
is only a number,char
is a number, a letter and also an atom of object representation. It's also implementation-defined as to whether it is signed or unsigned – Delunaresult1 = op1 | op2;
is fine.result2 = op1 || op2;
is well formed but clearly wrong and the warning here makes sense – Nashbarbool
type, the compiler will use the CPUs underlying bit-wise operator as it only cares about one bit and the others should all be zero and don't need to be tested. – Nashbarchar
is a bad type, because you don't know which of those 3 meanings applies to a given instance. Why do you thinkstd::byte
was added? – Deluna'||' was probably intended
when || almost certainly wasn't intended. – Nashbar||
with chars. If you don't like the linter rule, disable it in the options. – Canticleusing "|" with non-integer type
and omit the'||' was probably intended
– Nashbarunsigned
operands, since bitwise operations onunsigned
operands to produce anunsigned
result is a reasonably common use case. If so, one option to stop the warning with bitwise|
might be to explicitly convert operands tounsigned
, do the bitwise operation, and explicitly convert the result tounsigned char
e.g.unsigned char result1 = (unsigned char)((unsigned)op1 | (unsigned)op2);
. Ifunsigned
doesn't work,int
might - either way, I suggest this only as a possible workaround for an analyser bug, not as a recommended code practice. – Twibillunsigned short result3 = op1 | op2; unsigned short result4 = op1 || op2; unsigned short op5 = 0x1; unsigned short op6 = 0x3; unsigned short result5 = op5 | op6; unsigned short result6 = op5 || op6;
– Defendant