2

I was trying to compile some Arduino code on the PC for testing when I noticed some strange syntax for numerical binary constants.

Convetion seems to be to declare them like so:

    static const uint8_t smiley[] = {
        B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10100101,
        B10011001,
        B01000010,
        B00111100 };

However, when I try to compile this with g++ I get

error: ‘B00111100’ was not declared in this scope

Now when I exchange this for B for the standard C/C++ prefix 0B it works, but I don't want to change the code that I want so simulate!

Is there some clever macro magic at play here?

4

There is a file (binary.h) with every possible permutation of number between 0 and 255 represented as binary in it. They're stored as C-preprocessor macros:

#define B0 0
#define B00 0
#define B000 0
#define B0000 0
#define B00000 0
#define B000000 0
#define B0000000 0
#define B00000000 0
#define B1 1
#define B01 1
#define B001 1
#define B0001 1
#define B00001 1
#define B000001 1
#define B0000001 1
#define B00000001 1
#define B10 2
#define B010 2
#define B0010 2
#define B00010 2
#define B000010 2
#define B0000010 2
#define B00000010 2
... etc ...

Quite why Arduino decided to do this is anyone's guess. It makes, as you have seen, for non-portable code.

Personally, I never use (and would never recommend any one else should use) those macros, and instead use the GCC standard binary literal representation 0b.....

  • 3
    1/2 a christmas tree ... lol – jsotola Dec 11 '18 at 1:44
  • 2
    The reason they did that is because GCC didn't have the binary representation when Arduino got started. Now the macros still need to be there in order to avoid breaking old code written using them. At this point, I do agree that people should be using the standard binary representation. Yes, there are ancient IDE versions where that code won't compile, but you can only go so far with backwards compatibility. – per1234 Dec 11 '18 at 3:08
  • @jsotola Half a Christmas binary tree ;) – Majenko Dec 11 '18 at 8:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.