Compiler problem

Consider the following (nonsensical) program.

It compiles without error in Arduino and Engeria.
In both cloud and Particle Dev, it fails with:
crap.cpp:5:1: error: expected unqualified-id before 'else’
else if (res & 2);
^
It sure looks lik good C/C++ to me. Any insights?

Al

void setup()
    {
    }

void loop()
    {
    int res, rr;

    if (res & 1)
        {
        rr = 1;
        }
    else if (res & 2)
        {
        rr = 2;
        }
    }

That C code compiles here without error. No C++ syntax used. File name is .cpp so compiler will treat it as C++.
Perhaps you have a non-printable character within the source?

(PS: your question has an unrelated error with the semicolon after (res & 2).

Also, most compilers will give a warning that res has no value assigned before its first use.

It’s a .ino - which apparently is converted to .cpp somewhere under the hood.

It (the exact same file) compiles without error in Arduino and Energia, presumably with similar machination between .ino source and the compiler.

I don’t understand the comment about the semicolon.

I agree that there should be a warning about unassigned value, but there is none.

This is not a real program - it’s boiled down to a minimum which triggers the Particle Compiler error.

It is the Particle/Arduino preprocessor that is messing you up. This is the nice part of Arduino-land that lets you avoid function prototypes for forward references and lots of other stuff, but it is messed up by single statement if’s.

You can turn it off (and then write strictly in C/C++) with this at the top of your file:

#pragma SPARK_NO_PREPROCESSOR

You can also make it compile by adding curly braces around the else clause so it is no longer a single statement:

void setup()
    {
    }

void loop()
    {
    int res, rr;

    if (res & 1)
        {
        rr = 1;
        }
    else {if (res & 2)
        {
        rr = 2;
        }}
    }
1 Like

This is a not unknown :wink: quirk of the preprocessor that does the C -> C++ wrapping.

To get rid of this, you can add these lines to the top of your sketch.

#pragma SPARK_NO_PREPROCESSOR
#include "Particle.h"

So much time, and we still manage to answer at the same minute - @bko :+1:

1 Like