V676. It is incorrect to compare the variable of BOOL type with TRUE.


The analyzer has detected an issue when a BOOL value is compared to the TRUE constant (or 1). This is a potential error, since the value "true" may be presented by any non-zero number.

Let's recall the difference between the types 'bool' and 'BOOL'.

The following construct:

bool x = ....;
if (x == true) ....

is absolutely correct. The 'bool' type may take only two values: true and false.

When dealing with the BOOL type, such checks are inadmissible. The BOOL type is actually the 'int' type, which means that it can store values other than zero and one. Any non-zero value is considered to be "true".

Values other than 1 may be returned, for example, by functions from Windows SDK.

The constants FALSE/TRUE are declared in the following way:

#define FALSE               0
#define TRUE                1

It means that the following comparison may fail:

BOOL ret = Some_SDK_Function();
if (TRUE == ret)
{
  // do something
}

It is not guaranteed that it is 1 that the function Some_SDK_Function() will return, if executed successfully. The correct code should look this:

if (FALSE != ret)

or:

if (ret)

For more information on this subject, I recommend you to study FAQ on the website CodeGuru: Visual C++ General: What is the difference between 'BOOL' and 'bool'?

When found in a real application, the error may look something like this:

if (CDialog::OnInitDialog() != TRUE )
  return FALSE;

The CDialog::OnInitDialog() function's description reads: "If OnInitDialog returns nonzero, Windows sets the input focus to the default location, the first control in the dialog box. The application can return 0 only if it has explicitly set the input focus to one of the controls in the dialog box."

Notice that there is not a word about TRUE or 1. The fixed code should be like this:

if (CDialog::OnInitDialog() == FALSE)
  return FALSE;

This code may run successfully for a long time, but no one can say for sure that it will be always like that.

A few words concerning false positives. The programmer may be sometimes absolutely sure that a BOOL variable will always have 0 or 1. In this case, you may suppress a false positive using one of the several techniques. However, you'd still better fix your code: it will be more reliable from the viewpoint of future refactoring.

This diagnostic is close to the V642 diagnostic.

According to Common Weakness Enumeration, potential errors found by using this diagnostic are classified as CWE-253.

You can look at examples of errors detected by the V676 diagnostic.


Bugs Found

Checked Projects
355
Collected Errors
13 303