What am I missing RE 'bool' variables?

I’m experiencing something weird that seems to be related to using a [bool] variable in an if clause. I say “seems” because I haven’t seen this in the past,so perhaps I’m missing something more basic?

If I try to compile with the following in my project, the compiler fails:

     if (DoorClosed) 
     {
       DistanceTravelled = 0;
        PctOpen = 0.0;
     }
     else if (DoorOpen)
     {
        PctOpen = 100.0;
     }
     else
     {
        PctOpen = ((double) (DistanceTravelled / 4 )) / FullOpenDist * 100.0;
     }

‘DoorClosed’ and ‘DoorOpen’ are global variables defined like this:

    bool DoorClosed = false;  // Input high when door Closed
    bool DoorOpen = false;      // Input high when door Open

The compiler gives me the following error:

"garageminder.cpp:7:1: error: expected unqualified-id before 'else'
 else if (DoorOpen);
 ^

However…

if I change the code code like this, the software compiles:

     if (DoorClosed == true)
     {
       DistanceTravelled = 0;
        PctOpen = 0.0;
     }
     else if (DoorOpen == true)
     {
        PctOpen = 100.0;
     }
     else
     {
        PctOpen = ((double) (DistanceTravelled / 4 )) / FullOpenDist * 100.0;
     }

NOTE: In case it helps, the above code is in loop().

The really weird thing is that I have other code in the same project where I’ve put a bool variable in an if statement, and
the compiler did not complain! So is this some weird red herring or have I missed something basic?

Hi @tedb

I have noticed this too and it is the Wiring preprocessor that is messing things up. The preprocessor makes it so you can write Wiring language instead of straight C/C++ but it can screw up. You can turn the preprocessor off with a pragma and include application.h or you can use your second code.

I think a lot of experienced people write if statements like this (with the curly-braces wherever you happen to like them):

  if (true == DoorClosed) {
    ...
  } else {
    ...
  }

with the constant side first since then if you forget a double-equals and use single equals instead, the compile will fail rather that silently assign to your variable.

1 Like