2

Arduino.h defines LOW as 0x0 and HIGH as 0x1. Does the Arduino API intend to expose that fact? Does it guarantee that this will always be that way?

In other words, what is the intended purpose of these manifest constants: LOW and HIGH?

  • Is this purely cosmetic mnemonics added as an alternative for 0/1 and false/true, for those who like LOW/HIGH better?

  • Or is this an attempt to abstract/isolate the user's source code from the actual representation of LOW and HIGH (e.g. in case the representation changes in the future)?

The underlying reason for this question is to figure out whether code like

digitalWrite(some_pin, true);
digitalWrite(some_other_pin, !digitalRead(some_other_pin));

is a good programming practice. (If LOW and HIGH are there to abstract the user's code form their actual values then code like that is definitely a bad programming practice.)

1 Answers1

4

The underlying reason for this question is to figure out whether code like

digitalWrite(some_pin, true);
digitalWrite(some_other_pin, !digitalRead(some_other_pin));

is a good programming practice. (If LOW and HIGH are there to abstract the user's code form their actual values then code like that is definitely a bad programming practice.)

Strictly speaking, no, that is not good programming practice.

digitalRead() returns an int. digitalWrite() expects an int. Using ! converts the int into a bool and then it's promoted back to an int again.

In fact, the "next gen" Arduino core API changes HIGH and LOW from a simple int to an enum - and that struggles with casting through bool like that:

typedef enum {
  LOW     = 0,
  HIGH    = 1,
  CHANGE  = 2,
  FALLING = 3,
  RISING  = 4,
} PinStatus;

You can see the problems that causes here.

Majenko
  • 105,095
  • 5
  • 79
  • 137