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.)
2
Answers
lnt-logical-bitwise-mismatch
is a Visual Studio linter rule. It tells you that logical operators should only be used with booleans:and bitwise operatos should only be used with integers, not chars:
See https://learn.microsoft.com/en-us/cpp/ide/lnt-logical-bitwise-mismatch?view=msvc-170 for more details
If you don’t want this warning, you can configure the linter in "Options" -> "Text Editor" -> "C/C++" -> "Code Style" -> "Linter": https://learn.microsoft.com/en-us/cpp/ide/cpp-linter-overview?view=msvc-170#configure-the-linter
I’m not saying that these rules make sense. I’m just answering why you get the squiggles and how you can avoid it. The usefulness of these rules is a different question.
You can
configure the linter in "Options" -> "Text Editor" -> "C/C++" -> "Code Style" -> "Linter" as suggested by the other answer.
I do not know if that is saved to the project file to switch off the warning for other people
type cast to integer (or potentially to unsigned char(?)) as suggested in the comments. You may
//explain why
.change the type of the variables. Presumably you use char for some reason (input output communication…); then the type cast may take place somewhere closer to that reason
possibly there is #pragma or something to tell the linter to shut up (??)
(Or probably not — because type cast is a simple solution.)