>
>
>
V768. Variable is of enum type. It is s…


V768. Variable is of enum type. It is suspicious 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;
  ....
 }

This diagnostic is classified as:

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