Why if I put more than one instruction under IF won't make ELSE IF work? [SOLVED]

Sorry for my bad explanation, here's the code:

      moveA = random(0,2);
      if (moveA == 0) // IF condition
        Serial.print(a0); // First instruction, the code works correctly
        strcpy(a3, a0); // when I add this, it won't even upload to Arduino**
      else if (moveA == 1) // highlighted as error <Compilation error: 'else' without a previous 'if'>
        Serial.print(a1);
        strcpy(a4, a1);
      else if (moveA == 2)
        Serial.print(a2);
        strcpy(a5; a2);
      delay(200);

** after adding the second instruction under IF, the code doesn't upload to Arduino and an error says that I can't put else if (on the next line) without a previous IF (that is actually two lines before).
this is the error:
Compilation error: 'else' without a previous 'if'
any ideas?

Your answer is right in the Arduino Reference documentation: https://www.arduino.cc/reference/en/language/structure/control-structure/if/

Because you have multiple else if conditions, you need brackets:

Not quite. First, they are braces {}, not brackets []. Nor parentheses () while we are at it.

And this is fine

    if (moveA == 0)
        Serial.print(a0); // First instruction, the code works correctly
    else if (moveA == 1)
        Serial.print(a1);
    else if (moveA == 2)
        Serial.print(a2);

What required the braces is that when multiple simple statements need to be executed in their entirety or not according to the if condition, you need to make a block statement of them by enclosing them in braces.

a7

1 Like

Has the OP tried using these "{" and "}"?

https://www.w3schools.blog/c-if-else#:~:text=C%20if%20else%20-%20W3schools%20C%20if%20else,or%20actions%2C%20if%20the%20particular%20condition%20is%20true.

Can't believe I was stuck for this! thank uu

I always (ok, nearly always) use braces, even when there's only one line to follow. That way a) I'm in the habit and b) if I go back and add a second line, the braces are already there and I can't forget to add them.

1 Like

I never (ok, nearly never) use braces when none are needed syntactically.

That way a) I occasionally srsly regret not doing when I b) forget to add them when adding a line or two of code.

A rare bit of excitement from time to time.

It stems from wanting to see as little ink as possible. And plenty of white space to make up for it. :expressionless:

a7

1 Like

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