diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -2610,6 +2610,7 @@ nextToken(); handleAttributes(); if (FormatTok->is(tok::l_brace)) { + const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if); FormatTok->setFinalizedType(TT_ElseLBrace); ElseLeftBrace = FormatTok; CompoundStatementIndenter Indenter(this, Style, Line->Level); @@ -2621,7 +2622,7 @@ KeepElseBraces = KeepElseBraces || ElseBlockKind == IfStmtKind::IfOnly || ElseBlockKind == IfStmtKind::IfElseIf; - } else if (IfLBrace && !IfLBrace->Optional) { + } else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) { KeepElseBraces = true; assert(ElseLeftBrace->MatchingParen); markOptionalBraces(ElseLeftBrace); diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -25576,6 +25576,17 @@ " g;", Style); + verifyFormat("if (a) {\n" + " b;\n" + " c;\n" + "} else { // comment\n" + " if (d) {\n" + " e;\n" + " f;\n" + " }\n" + "}", + Style); + verifyFormat("if (a)\n" " b;\n" "else if (c)\n"