V562. Bool type value is compared with value of N. Consider inspecting the expression.
The analyzer detected an issue when a value of the bool type is compared to a number. Most likely, there is an error.
Consider this sample:
if (0 < A < 5)
The programmer not familiar with the C++ language well wanted to use this code to check whether the value lies within the range between 0 and 5. Actually, the calculations will be performed in the following sequence: ((0 < A) < 5). The result of the "0 < A" expression has the bool type and therefore is always below 5.
This is the correct code for the check:
if (0 < A && A < 5)
The previous example resembles a mistake usually made by students. But even skilled developers are not secure from such errors.
Let's consider another sample:
if (! (fp = fopen(filename, "wb")) == -1) {
perror("opening image file failed");
exit(1);
}
Here we have 2 errors of different types at once. First, the "fopen" function returns the pointer and compares the returned value to NULL. The programmer confused the "fopen" function with "open" function, the latter being that very function that returns "-1" if there is an error. Second, the negation operation "!" is executed first and only then the value is compared to "-1". There is no sense in comparing a value of the bool type to "-1" and that is why the analyzer warned us about the code.
This is the correct code:
if ( (fp = fopen(filename, "wb")) == NULL) {
perror("opening image file failed");
exit(1);
}
This diagnostic is classified as:
|
You can look at examples of errors detected by the V562 diagnostic. |