Error with definition of #define

I am trying to define a #define in Arduino but I have error on line 7, this is the error shown:

expected primary-expression before '{' token

This is my code:

unsigned long timeout_start;
unsigned long timeout_ms;

#define TIMEOUT_2000MS 2000
#define ERROR_TIMEOUT 1
#define TIMEOUT_START { timeout_start = millis(); }
#define TIMEOUT_CHECK { if (millis() - timeout_start > timeout_ms) return ERROR_TIMEOUT; }

void setup() {
  Serial.begin(115200);
  timeout_ms = TIMEOUT_2000MS;
  TIMEOUT_START
  while (!Serial.available() && TIMEOUT_CHECK) {
    delay(1);
  }
}

void loop() {
}

Someone could tell me what is my mistake?

Not posting the error message.

That one

Hint: try the macro expansion manually.

This is the error:

sketch_nov04a\sketch_nov04a.ino: In function 'void setup()':

sketch_nov04a:7:23: error: expected primary-expression before '{' token

#define TIMEOUT_CHECK { if (millis() - timeout_start > timeout_ms) return ERROR_TIMEOUT; }

sketch_nov04a\sketch_nov04a.ino:13:33: note: in expansion of macro 'TIMEOUT_CHECK'

while (!Serial.available() && TIMEOUT_CHECK) {

That is PART of the error message!

Here is my part of the answer :
All you need to do is change . . . .

What do YOU get when YOU expand the macro? Makes no sense to me.

I already made the change, but the error is still there, on line 8:

Here is the code:

unsigned long timeout_start;
unsigned long timeout_ms;

#define TIMEOUT_2000MS 2000
#define ERROR_TIMEOUT 1
#define TIMEOUT_START { timeout_start = millis(); }
#define TIMEOUT_CHECK {
if ( (millis() - timeout_start) > timeout_ms )
  return ERROR_TIMEOUT;
}

void setup() {
  Serial.begin(115200);
  timeout_ms = TIMEOUT_2000MS;
  TIMEOUT_START
  while (!Serial.available() && TIMEOUT_CHECK) {
    delay(1);
  }
}

void loop() {
}

Here is the error message:

sketch_nov04a:8:1: error: expected unqualified-id before 'if'
if ( (millis() - timeout_start) > timeout_ms )

sketch_nov04a:10:1: error: expected declaration before '}' token

}
exit status 1
expected unqualified-id before 'if'

Your concept of the macro as a pseudo function is all wrong.
Your definition of the macro is very wrong with a lack of line continuation operators , so it looks like you got off lightly.

What you see

What the compiler sees

That's what the expansion does.

#define TIMEOUT_CHECK ( (millis() - timeout_start) > timeout_ms )

Looks better to me

You CAN use your existing definition of TIMEOUT_CHECK but you have to use it as a statement. You can't put a statement in an expression. You could use it this way:

#define TIMEOUT_CHECK { if (millis() - timeout_start > timeout_ms) return ERROR_TIMEOUT; }

while (!Serial.available()) {
    TIMEOUT_CHECK
    delay(1);
  }

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.