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


Do you make errors in the code?

Check your code
with PVS-Studio

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

goto PVS-Studio;
We use cookies for the analysis of events to improve our content and make user interaction more convenient. By continuing the view of our web-pages you accept the terms of using these files. You can find out more about cookie-files and privacy policy or close the notification, by clicking on the button. Learn More →
Do not show