Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Which is better/more generally accepted?

This:

if(condition)
{
  statement;
}

Or:

if(condition)
  statement;

I tend to prefer the first one, because I think it makes it easier to tell what actually belongs in the if block, it saves others from adding the braces later (or creating a bug by forgetting to), and it makes all your if statements uniform instead of some with braces and some without. The second one, however, is still syntactically correct and definitely more compact. I'm curious to see which is more generally preferred by others though.

share|improve this question
2  
But you have your opening brace in the wrong position. That much is certain. –  Christian Mann Nov 6 '10 at 7:38
1  
Since you didn't specify a language... What about statement if condition;? –  Dave Sherohman Sep 9 '11 at 11:44
show 5 more comments

17 Answers

up vote 127 down vote accepted

The first is better because the second is error-prone. For example, let's say you are temporarily commenting out code to debug something:

if(condition) 
//      statement;
otherStatement;

Or adding code in a hurry:

if(condition) 
    statement;
    otherStatement;

This is obviously bad. On the other hand, the first one does feel too verbose at times. Therefore, I prefer to just put everything on one line if it's sufficiently short and simple:

if(condition) statement;

This cuts down on syntactic noise while making the construct look like it does what it actually does, making it less error-prone. Provided that this syntax is only used for very simple, short conditions and statements, I find it perfectly readable.

share|improve this answer
33  
Good point about putting everything on one line. –  Neil Aitken Nov 3 '10 at 14:50
7  
@artjomka: If statement is long, and has to go on its own line, then I use braces for readability. The point is that you want the shortest, least syntactically noisy construct that is unambiguous to a human who is reading it quickly rather than scrutinizing it. –  dsimcha Nov 3 '10 at 14:56
15  
I prefer the one with braces for the reasons already mentioned. I don't like the one-liner, because it is not immediately obvious what happens when I step over the line in the debugger. I have to take the separate step to see what condition evaluates to. –  Jim A Nov 3 '10 at 16:25
10  
@TMN whitespace is free, monitors are big and your brain learns to recognise the shape which helps you parse the code. –  Murph Nov 3 '10 at 20:52
4  
@Murph: whitespace is free? I must have missed that. On my screen, it takes up really much space. Much more than 50% actually. Which in my book seems like a big waste. Personally, I like to maximize content per square centimeter in code. –  Konrad Rudolph Nov 4 '10 at 16:56
show 14 more comments

I always use brackets just to be safe.

It's fine when you write it, but you know somebody will come along in the future and insert another statement without putting brackets around it.

share|improve this answer
17  
Have people really seen this happen? I don't think I've ever seen this in 10 years of programming. Maybe I've just been too sheltered. :) –  David Nov 3 '10 at 15:35
9  
I'd love to say no, but sadly I have seen it. –  Neil Aitken Nov 3 '10 at 15:58
13  
You always use brackets so that you never forget to use brackets - its as simple as that. –  Murph Nov 3 '10 at 20:49
12  
+1 to @Murph. Same reason I use my turn signals when nobody's around--and in parking lots! –  Dan Ray Nov 3 '10 at 23:58
7  
This is good practice to help prevent errors when merging from branch-to-trunk or across branches. –  JBRWilkinson Nov 4 '10 at 11:01
show 4 more comments

I prefer the version without braces where possible.

The following explanation is longish. Please bear with me. I will give a compelling reason for me to prefer this style. I will also explain why I think that the usual counter-argument doesn’t hold.

(Near-) empty lines are a waste

The reason for this is that the closing brace requires an extra line of code – and so does the opening brace, depending on style.1

Is this a big deal? Superficially, no. After all, most people also put empty lines in their code to separate logically slightly independent blocks, which vastly improves readability.

However, I detest wasting vertical space. Modern monitors actually have ample horizontal space. But vertical space is still very, very limited (unless you use a monitor turned upright, which isn’t that uncommon). This limited vertical space is a problem: it’s widely acknowledged that individual methods should be as short as possible, and that corresponding braces (or other block delimiters) should be no more than a screen height in difference so that you may see the entire block without scrolling.

This is a fundamental problem: once you can’t see the entire block on your screen any longer, it gets complicated to grasp.

As a consequence, I detest redundant empty lines. Where single empty lines are crucial to delimit independent blocks (just look at the visual appearance of this text), consecutive empty lines are a very bad style in my book (and in my experience they are usually a sign of novice programmers).

Likewise, lines which simply hold a brace, and which could be economised, should be. A single-statement block which is delimited by braces wastes one to two lines. With only 50-ish lines per screen height, this is noticeable.

Omitting braces maybe does no harm

There is just one argument against omitting braces: that someone will later add another statement to the block in question and will forget to add the braces, thus inadvertently changing the semantics of the code.

This would indeed be a big deal.

But in my experience, it isn’t. I’m a sloppy programmer; and yet, in my decade of programming experience, I can honestly say that I have not once forgotten to add the braces when adding an extra statement to a singleton block.

I even find it implausible that this should be a common mistake: blocks are a fundamental part of programming. Block level resolution and scoping is an automatic, ingrained mental process for programmers. The brain just does it (otherwise, reasoning about programming would be much harder). There is no additional mental effort required to remember putting the braces: the programmer also remembers to indent the newly added statement correctly, after all; so the programmer has already mentally processed that a block is involved.

Now, I am not saying that omitting braces doesn’t cause mistakes. What I’m saying is that we have no evidence one way or the other. We simply don’t know whether it causes harm.

So until someone can show me hard data, collected from scientific experiments, demonstrating that this is indeed an issue in practice, this theory remains a “just-so story”: a very compelling hypothesis that has never been put to the test, and that must not be used as an argument.


1 This problem is sometimes solved by putting everything – including the braces – on the same line:

if (condition)
{ do_something(); }

However, I believe it’s safe to say that most people despise this. Furthermore, it would have the same problems as the variant without braces so it’s the worst of both worlds.

share|improve this answer
5  
Omitting braces harms readability and can easily cause issues when the code is modified. –  Josh K Nov 3 '10 at 16:20
14  
@Josh: the first claim is ridiculous, as languages such as Python show (back it up with evidence if you think otherwise). The second has been countered in my answer. Do you have evidence to back it up? Otherwise your comment is an indication that you haven’t actually read my text. Please do so before criticising it. –  Konrad Rudolph Nov 3 '10 at 16:25
8  
+1 for your thoughts, but I think your position is self-defeating. You say "show me hard data, collected from scientific experiments, showing that this is indeed an issue in practice" and yet fall back on anecdotal experience (your own) to defend your position. You say, "in my experience...in my decade of experience...I find it implausible..." and so forth. Can you show hard data, collected from scientific experiments, supporting your claim, "Omitting braces does no harm"? Personal experience is fine when supporting an opinion, but don't ask for more "evidence" than you're willing to give. –  bedwyr Nov 3 '10 at 18:59
3  
@bedwyr: there’s a qualitative difference, though. First, I make it clear that I will actually be persuaded by data, and I make it equally clear that mine is merely a hypothesis, not backed up by data. Secondly, I have stated an (at least to me) plausible argument for my belief that the claim is false and why it needs to be corroborated. Which leads me to thirdly: the onus here is on the opposition to prove their claim, not on me to disprove it. And in addition to the plausibility problem, I have shown one unrelated factual argument supporting my coding style. –  Konrad Rudolph Nov 3 '10 at 19:52
4  
@Konrad - python does not show otherwise because the indentation is significant and hence the braces are implicit. Good bright programmers, the type who are here, probably won't make the mistake often if at all (in a lot of years I've probably seen issue with on only a couple of occasions) but there are a lot of rather less good programmers out there who do do stupid things which is one of the reasons why coding standards are needed in the first place. (And because deadlines and stress can make the best of us less good.) –  Murph Nov 3 '10 at 21:02
show 7 more comments

I go with the second. It's more succinct and less verbose.

I try not to write to the lowest common denominator, so I expect that other developers know how to write one of the single most common control flow structures in programming today.

share|improve this answer
10  
absolutely! after all, if the code was hard to write, it should be hard to maintain, too! ;-) –  Steven A. Lowe Nov 3 '10 at 23:52
2  
@Steven If you forget braces, I think there are other problems here. –  TheLQ Nov 4 '10 at 1:06
5  
@SnOrfus: somewhat sarcastic, since the extra 2 characters are trivial overhead and prevent a very common maintenance mistake. Your Mileage May Vary ;-) –  Steven A. Lowe Nov 8 '10 at 4:32
1  
To me the indenting makes it clear what's going on. The first form burns extra screen space and thus is a negative to me. –  Loren Pechtel Jul 27 '12 at 16:58
show 3 more comments

I'd use the following (the consensus here):

if (condition) {
    any_number_of_statements;
}

Also possible:

if(condition) single_compact_statement;

Not so good, especially in C/C++-like languages:

if(condition) 
    single_compact_statement;

(No choice here in Python ;-)


In Perl, you'd use:

$C = $A**3 if $A != $B;

or

$C = $A**3 unless $A == $B;

(This is not pseudocode ;-)

share|improve this answer
1  
My thoughts exactly. If the single statement looks good on a single line after the if clause, I don't use braces. For any other if statement (or any statement that uses multiple lines), I always use braces. In particular, if there's an else clause, each case always has braces. –  eswald Nov 3 '10 at 17:33
9  
I've never seen somebody confuse perl with pseudocode before. Random characters yes, pseudocode - no. –  Joe D Nov 3 '10 at 20:24
3  
I wonder if anyone's made a Perl program generator just by hooking up /dev/random to a Perl interpreter... –  Christian Mann Nov 6 '10 at 7:40
show 1 more comment

No braces. If some other programmer adds a second statement to my code it's no more my fault then if I let someone drive my car and they went over a cliff.

share|improve this answer
3  
Exactly! It's not our fault he/she doesn't know the syntax. –  kirk.burleson Nov 11 '10 at 3:44
3  
Bad example. A good one is a car with misplaced pedals - gas instead of brake. It's your car, so you don't care about anybody else. It's there problem that they don't know about your unique positioning of pedals. Are you a good car engineer in this case? –  yegor256 Jan 30 '13 at 14:33
show 1 more comment

I use the braces method - for all the reasons above plus one more.

Code merges. It's been known to happen on projects I've worked on that single-statement ifs have been broken by automatic merges. The scary thing is the indentation looks right even though the code is wrong, so this type of bug is hard to spot.

So I go with braces - on their own lines. It's easier to spot the levels that way. Yes, it does waste vertical screen real estate and that's a genuine downside. On balance though, I think it's worth it.

share|improve this answer
3  
+1 Code merges are the real reason to use braces. –  Residuum Sep 9 '11 at 14:02
add comment

We have had this argument more than once here, and the overall consensus is to always use braces. The main reasons are about readability/maintainability.

If you need to add code to the if block, you don't need to remember/search for braces. When future programmers read the code, the braces are always unambiguous.

On the plus side, ReSharper will automatically add the braces for lazy programmers in Visual Studio, and I assume there are addons for other IDEs that will do so as well.

share|improve this answer
3  
I categorically don’t buy the readability claim. Python is one of the most readable languages there is and it doesn’t need delimiters. That claim is just not true. I also don’t buy the maintainability claim because it’s so far unproven and still repeatedly rehashed. But in this case I’m actually very interested in empirical evidence. This is something that a study could very easily find out, and settle once and for all. –  Konrad Rudolph Nov 3 '10 at 16:42
show 6 more comments

I use the first syntax, almost without exception. Because it cannot be misinterpreted.

"Don't make me think" doesn't just apply to user-interfaces, y'all ;-)

share|improve this answer
4  
I used to do this, but I was won over by the argument that programmers need to know the language and they should be made to think. –  kirk.burleson Nov 11 '10 at 3:46
2  
I consider it common courtesy...to my future self. –  Steven A. Lowe Nov 11 '10 at 6:36
add comment

I personally prefer the second. The first one looks ugly, awkward, and wastes horizontal space. The main problems with the second one are macros and people modifying your code at a later point getting it wrong.

To this, I say "don't use macros". I also say, "indent your damn code correctly". Considering how every text editor/IDE used for programming does indentation automatically, this shouldn't be that hard to do. When writing code in Emacs, I would use the auto-indent to identify if I wrote something wrong on a previous line. Anytime Emacs starts screwing up indentation, I usually know I've done something wrong.

In practice, I end up following whatever coding convention has been set before me. But these ones annoy me (and makes me much happier when I code in Python and this entire bracket disaster is gone):

if (condition) {
    statement;
} // stupid extra brace looks ugly

Then

if (condition) // the brackets have now just become noise
{ statement; } // also can't see the indentation, harder to read

Although honestly, two statements in an if statement annoy me far more than a single statement. Mostly because then brackets are required and it still looks funny with only two statements in the if statement.

share|improve this answer
show 1 more comment

I use the two-line version without braces (the 2nd form), but not to save space.

I use that form because I find it more readable, more visually appealing, and easier to type. I only use that form if those conditions are met; i.e. the if condition has to fit nicely on a single line, and the corresponding statement has to fit nicely on the following line. If that is not the case, then I will use braces to improve readability.

If I use this form, I make sure that there is an empty line (or a line containing only a brace) before and after the if statement (or above the comment, if present). While this is not a rule that I consciously follow, I notice it now after reading this question.

Conserving screen space is not a priority for me. If I needed more space I would use a larger monitor. My screen is already large enough for me to read anything that I might need to focus my attention on. It's unlikely that I would need to focus on so many lines of code at one time that they take up my entire screen. If there is so much nesting going on with a chunk of code that I can't understand it without viewing more of it at one time, then I would have to consider whether the logic could be better represented by refactoring.

Below are some examples that demonstrate how I use this form of the if statement.

    string GuardConditions(Plan planForWorldDomination)
    {
        if (planForWorldDomination == null)
            throw new ArgumentNullException("planForWorldDomination");

        if (!planForWorldDomination.IsComplete())
            return "Doh!";

        planForWorldDomination.Execute();
    }

    void ProcessingLogic()
    {
        OneBlankLineAbove();

        if (simpleCondition)
            simpleStatement();

        OneBlankLineBelow();
        OneBlankLineAbove();

        // optional comment on the line above an if statement
        if (simpleCondition)
            simpleStatement();

        OneBlankLineBelow();
    }

    void Assignment(string drive)
    {
        OneBlankLineAbove();

        string prompt;
        if (simpleCondition)
            prompt = "simple assignment";
        else
            prompt = null;

        OneBlankLineBelow();
    }

    string Return()
    {
        OneBlankLineAbove();

        if (simpleCondition)
            return "simple return";
        else
            return null;

        OneBlankLineBelow();
    }
share|improve this answer
1  
+1 for readability. –  kirk.burleson Nov 11 '10 at 3:52
add comment

Braces. Always. I'm kind of the fan of them, because it gives code some consistency. And also as @dsimcha wrote - less chance for errors on adding additional lines of code.

"Ugliness" of braces around single line of code are less harmful than additional work which is probable in those cases with debugging and/or adding code.

share|improve this answer
1  
I've never seen anyone make the error you're speaking of. –  kirk.burleson Nov 11 '10 at 3:51
1  
I've just made it yesterday on someone elses piece of code. :-) I just wonder how the upstream will look on, among other additions to the code, adding braces on all of his if's because he really seems to be from different side than me on this. :-) (calm down, I'm joking, edited just what I had to...) –  Vedran Krivokuća Nov 11 '10 at 13:37
add comment

Personally I go with brackets.

Why?

Well if anyone comes along and needs to add code into the if statement it's 100% clear where the scope is.

It keeps the format of if statements consistent no matter how many statements there are in the block.

However, if the project style is to go without, stick to that.

share|improve this answer
add comment

I almost always use the brackets just to be on the safe side. However, sometimes if the contents of the block are really short I'll do leave them off and make it a one-liner like so:

if (x==5) Console.WriteLine("It's a five!");
share|improve this answer
2  
Brevity for sake of readability? Absolutely not. It's code, not a golf contest. –  Josh K Nov 3 '10 at 15:39
3  
I think readability is a great reason for brevity, personally. In any case: White-space doesn't count in my code-golf rulebook. –  JohnFx Nov 3 '10 at 15:58
2  
Then don't abuse it. I'm not saying use it as a coding standard. There just happen to be a lot of times when you have a really short conditional followed by a really short single statement and this works well. For example an if (assert) log.write("assert failed"); –  JohnFx Nov 3 '10 at 21:42
show 3 more comments

I prefer braces for consistency, but not wasting too much white space (so more readably formatted code is in my limited field of view). So I write this for short enough lines:

If (cond) { statement; }
share|improve this answer
show 1 more comment

I usually use braces, but there are some cases where I don't.

object GetObject() {
    // calculate obj1
    if(obj1 != null)
        return obj1;

    // calculate obj2
    if(obj2 != null)
        return obj2;

    // calculate obj3
    if(obj3 != null)
        return obj3;

    return defaultObj;
}

To me, it would just be silly to add them there. If someone adds a statement after the return, we have bigger problems than scoping issues.

share|improve this answer
show 4 more comments

If IDE has code formatting available I do not use braces.

On the other hand, where code may be edited in other editors which does not support auto formatting it is dangerous not to put braces as mentioned in other posts. But even so I prefer not to use braces, and it has not been problem for me.

share|improve this answer
add comment

protected by ChrisF Jul 27 '12 at 15:53

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.