Is it a bad practice to use an if-statement without curly braces?

jerebear picture jerebear · Jan 23, 2010 · Viewed 123.5k times · Source

I've seen code like this:

if(statement)
    do this;
else
    do this;

However, I think this is more readable:

if(statement){
    do this;
}else{
    do this;
}

Since both methods work, is this simply a matter of preference which to use or would one way be recommended over the other?

Answer

clee picture clee · Jan 24, 2010

The problem with the first version is that if you go back and add a second statement to the if or else clauses without remembering to add the curly braces, your code will break in unexpected and amusing ways.

Maintainability-wise, it's always smarter to use the second form.

EDIT: Ned points this out in the comments, but it's worth linking to here, too, I think. This is not just some ivory-tower hypothetical bullshit: https://www.imperialviolet.org/2014/02/22/applebug.html