V562. It's odd to compare a bool type value with a value of N.


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


Do you make errors in the code?

Check your code
with PVS-Studio

Static code analysis
for C, C++, and C#

goto PVS-Studio;
On our website we use a cookie to collect information of a technical nature.
If you do not agree, please leave the site. Learn More →
Do not show again