Andrei Oniga
Andrei Oniga

Reputation: 8559

Comparing variable to constant doesn't work?

Having a background of programming in PHP and Javascript, it's sometimes hard to wrap my head around the behavior of C and C compilers in certain situations. One such situation that I've just come across (programming an AVR ATmega16 microcontroller) is comparing variables to defined constants, which apparently doesn't work:

#define SYS_STATE_IDLE 0;
//...

char systemState = SYS_STATE_IDLE;
/...

// Main function body
int main(void) {

    //...

    for(;;) {
        // Determine if a new key was pressed
        if (keyPressed()) {
            switch (systemState) {
                case SYS_STATE_IDLE:
                    break;
                default:
                    break;
            }
        }
    }

    return 0;
}

The compiler (AVR GCC) throws the following exception at the first case:

../SunTrackerMainController.c:103: error: expected ':' or '...' before ';' token
../SunTrackerMainController.c:103: error: expected expression before ':' token

I've tried the if statement as well:

if (systemState == SYS_STATE_IDLE) {
    // whatever
}

but the outcome is basically the same:

../SunTrackerMainController.c:109: error: expected ')' before ';' token

What is it that I'm doing wrong?

Upvotes: 0

Views: 121

Answers (4)

Some programmer dude
Some programmer dude

Reputation: 409384

You have to remember that the preprocessor replaces macros verbatim, so whenever it sees SYS_STATE_IDLE it replaces it with 0;, so the statement

case SYS_STATE_IDLE:

will be transformed to

case 0;:

The same when you try to use it inside the if, you get

if (systemState == 0;)

after macro replacement.

The preprocessor, as its name implies, is a step that is run before the compiler (the "pre" part) to process the source. It is its own micro-language inside the larger language that is C, and one that is terminated by newlines and not semicolons.

Upvotes: 4

Maroun
Maroun

Reputation: 95998

After the preprocessor, your code looks like this:

case 0;: {

Now you understand what is this ; the compiler is complaining about? To fix that, remove ; from define.

Upvotes: 0

Harshil Sharma
Harshil Sharma

Reputation: 2035

In #define Whatever you write after the definition name becomes its value. In this case, 0; is becoming the value of SYS_STATE_IDLE which should not include a semicolon being used as a numeric value.

Upvotes: 1

Tim
Tim

Reputation: 12174

Remove the ; from the end of your #define. At the moment the preprocessor is inserting a semicolon wherever you use SYS_STATE_IDLE, which you don't want.

#define SYS_STATE_IDLE 0

Upvotes: 5

Related Questions