Fix “'else' without a previous 'if'” in Arduino
The if has no braces and two statements, or a stray semicolon ends it early, so the else has nothing to attach to. Put both branches in { } braces.
Community draft — report a mistake
What you see
Button.ino: In function 'void loop()':
Button.ino:6:3: error: 'else' without a previous 'if'
else
^~~~
exit status 1
Compilation error: 'else' without a previous 'if'Button.ino: In function 'void loop()': Button.ino:6:3: error: 'else' without a previous 'if' else ^~~~ exit status 1 Compilation error: 'else' without a previous 'if'
The compiler reached an else but the if before it had already ended. Two lines under an if without braces is the classic cause:
// Wrong: only digitalWrite belongs to the if
if (digitalRead(2) == LOW)
digitalWrite(13, HIGH);
delay(100);
else
digitalWrite(13, LOW);
// Right
if (digitalRead(2) == LOW) {
digitalWrite(13, HIGH);
delay(100);
} else {
digitalWrite(13, LOW);
}Quick fix — try in order
- 1
Add braces to both branches
Without
{ }, an if controls only the next single statement. A second statement ends the if, and the else is orphaned. Always writeif (…) { … } else { … }. - 2
Remove a semicolon after the if
if (x > 10);— the;is an empty statement that completes the if. Delete it. - 3
Check braces before the else
An extra
}or a missing{between if and else breaks the pair. Auto Format (Ctrl+T) shows it. - 4
Spell it else if
elseiforelifdon’t exist in C++; it iselse if (…).
Why it happens
Why does the indentation look right?
C++ ignores indentation. Two indented lines under an if look like a block to people, but only the first belongs to the if unless braces are used.
Code coming from Python
Python uses indentation and elif; C++ uses braces and else if.
else after a closing brace and semicolon
if (a) { … }; followed by else fails the same way. No semicolon after the closing brace of an if.
Board-specific notes
Arduino IDE: Tools → Auto Format (Ctrl+T) re-indents according to the real structure, which makes this mistake visible.
Did this fix it?
Thanks — that helps us keep this page right.