Preview build — page text is a draft awaiting human review. Code badges come from real compiles. The flasher is real but not yet hardware-tested; the Playground is still a preview.
Compile error · syntax

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.

All boardsUpdated 3 Nov 2026

Community draft — report a mistake

What you see

OutputOutput
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. 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 write if (…) { … } else { … }.

  2. 2

    Remove a semicolon after the if

    if (x > 10); — the ; is an empty statement that completes the if. Delete it.

  3. 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. 4

    Spell it else if

    elseif or elif don’t exist in C++; it is else 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.

↑↓ to move · Enter to open