V732. Unary minus operator does not modify a bool type value.
The analyzer has detected an issue when the unary minus operator is applied to a value of type bool, BOOL, _Bool, and the like.
Consider the following example:
bool a;
....
bool b = -a;
This code doesn't make sense. The expressions in it are evaluated based on the following logic:
If a == false then 'false' turns into an int value 0. The '-' operator is then applied to this value, without affecting it of course, so it is 0 (i.e. false) that will be written into 'b'.
If a == true then 'true' turns into an int value 1. The '-' operator is then applied to it, resulting in value -1. However, -1 != 0; therefore, we'll still get value 'true' when writing -1 into a variable of the bool type.
So 'false' will remain 'false' and 'true' will remain 'true'.
The correct version of the assignment operation in the code above should use the '!' operator:
bool a;
....
bool b = !a;
Consider another example (BOOL is nothing but the int type):
BOOL a;
....
BOOL b = -a;
The unary minus can change the numerical value of a variable of type BOOL, but not its logical value. Any non-zero value will stand for 'true', while zero will still refer to 'false'.
Correct code:
BOOL a;
....
BOOL b = !a;
Note. Some programmers deliberately use constructs of the following pattern:
int val = Foo();
int s;
s = -(val<0);
The analyzer does produce warnings on constructs like that. There's no error here, but we still do not recommend writing your code that way.
Depending on the 'val' value, the 's' variable will be assigned either 0 or -1. Applying the unary minus to a logical expression only makes the code less comprehensible. Using the ternary operator instead would be more appropriate here.
s = (val < 0) ? -1 : 0;
This diagnostic is classified as:
|
You can look at examples of errors detected by the V732 diagnostic. |