Table of Contents

RDC11031: True value that is not -1

Severity: Warning  ·  Family: RDC (Rubberduck Core analyzers)  ·  Raised by: TrueValueIsNotMinusOneAnalyzer

A condition reads a constant that stands for True with a number other than -1 through an operator that works on the bits of the number. The condition does not mean what it says.

Such a constant is either one of your own, such as #Const DEV = 1, or a predefined one: Win32, Win64, Mac, VBA6, VBA7, Linux, Linux64 and DEBUG are 1 where they are true, as MS-VBA defines its own (predefined constants).

A condition is True when its value is not zero, so #If DEV Then with DEV = 1 compiles its branch, as expected. The logical operators (Not, And, Xor, Eqv, Imp) work on bits, though (MS-VBAL §5.6.9.8 Logical Operators), and True is -1, every bit set. Any other number gives a different answer:

  • Not 1 is -2, which is True. #If Not Win64 Then compiles its branch on 64-bit Windows.
  • 1 = True is False, because True is -1. So is 1 = -1.
  • 1 And 2 is 0, which is False, although both numbers are True in a condition.
  • 1 Xor True is -2, which is True, although both operands are True.

MS-VBA evaluates these conditions this way, and so does RD-VBA. The fix is in the code: test the constant by itself, or compare it with 0 (#If Win64 = 0 Then). A constant of your own can also be given the value True.

How it is raised

Situation Example What happens Resolution
Not of the constant. #If Not Win64 Then, or #Const DEV = 1, then #If Not DEV Then The branch is compiled: Not 1 is -2. #If Win64 = 0 Then, or #Const DEV = True
The constant compared with True or -1. #If Win64 = True Then, or Const DEBUGGING = 1, then If DEBUGGING = -1 Then The condition is False. #If Win64 Then, If DEBUGGING Then
And of two constants with no bit in common. #Const A = 2, then #If Win32 And A Then The branch is not compiled: 1 And 2 is 0. #If Win32 Then and #If A Then, nested, or give A the value True.
Xor, Eqv or Imp of the constant with a Boolean. #If Win64 Xor True Then The result is True or False for the wrong reason. #If Win64 = 0 Then
The value of a #Const made with such an operation. #Const RELEASE = Not DEBUG RELEASE is -2, which is True. #Const RELEASE = (DEBUG = 0)

A condition that tests the constant by itself (#If Win64 Then), Or, And of two predefined constants (#If VBA7 And Win64 Then), and a comparison with another number (#If Win64 = 1 Then) give the expected answer, and are not reported. Neither is an operation with a variable that holds a number, such as attributes And Not MASK: the bits are what such code is about.

The predefined constants exist in #If and #Const only, as in MS-VBA: code cannot read them. A constant the project defines (.rdproj, --define) is not known to the analyzer, which reads the module.

See also


ACCUEIL • HOME | ℹ️ BIENVENUE • WELCOME | 🧩 BÂTISSONS • BUILD | RD-VBAL | SDK | 🌐 rubberduckvba.ca