V768. The variable is of enum type. It is odd that it is used as a variable of a Boolean-type.


The analyzer detected a suspicious code fragment where a named constant from an enumeration or a variable of type 'enum' is used as a Boolean value. It is very likely to be a logic error.

Consider the following example:

enum Offset { left=10, right=15, top=20, bottom=25 };
void func(Offset offset) 
{
  .... 
  if (offset || i < 10)
  { 
    .... 
  } 
}

In this code, the 'offset' variable of type 'enum' is used as a Boolean value, but since all the values in the 'Offset' enumeration are non-zero, the condition will always be true. The analyzer warns us that the expression is incorrect and should be fixed, for example like this:

void func(Offset offset) 
{
  .... 
  if (offset == top || i < 10) 
  { 
    .... 
  } 
}

Here is one more example. Suppose we have the following enumeration:

enum NodeKind
{
  NK_Identifier = 64,
  ....
};

And the following class:

class Node
{
public:
  NodeKind _kind;
  bool IsKind(ptrdiff_t kind) const { return _kind == kind; }
};

The error then may look something like this:

void foo(Node node)
{
  if (node.IsKind(!NK_Identifier))
    return;
  ....
 }

The programmer expects the function to return if the current node is not an identifier. However, the '!NK_Identifier' expression evaluates to '0', while no such elements are found in the 'NodeKind' enumeration. As a result, the 'IsKind' method will always return 'false' and the function will continue running no matter if the current node is an identifier or not.

The fixed code should look like this:

void foo(Node node)
{
  if (!node.IsKind(NK_Identifier))
    return;
  ....
 }

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

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


Do you make errors in the code?

Check your code
with PVS-Studio

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

goto PVS-Studio;