If...else with multiple conditions

HI guys, another numpty question, sorry but what is wrong with this?

 if ((anval < switchlevel)&&(x > 5)); digitalWrite(2, HIGH);
  else (digitalWrite(2, LOW));

I’m getting ….

Compilation error: 'else' without a previous 'if'

If I leave out the &&(x > 5) condition all is ok.

Many thanks for any advise here


Remove that.

Can't be, unless you removed that semicolon also...

Thanks Paul, I said it was a numpty question, appreciate your help!

But do you understand why it was wrong before?

To be honest, not really, I tend to just bumble along working from other peoples examples and generally get where I want to be in the end. The syntax has always been a black art to be fair

That extra semicolon was ending the if-statement. The digitalWrite() after it would have been executed regardless of the condition, which would have been really confusing if the code had compiled and uploaded. Because the if-statement was ended, the else had no if-statement to belong to, hence the error message.

1 Like

The semi colon ';' is the end of a statement, so in your case it ended the if statement (prematurely)

Ah yes I’ve got it now, at least until the next time :wink: Thanks again.

1 Like

On this forum, we thank by marking the post that helped as the solution, not one of your own posts. It's just how the forum software works.