Search code examples
if-statementcoding-stylecurly-braces

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


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?


Solution

  • 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