9

This isn't a holy war, this isn't a question of "which is better".

What are the pros of using the following format for single statement if blocks.

if (x) print "x is true";

if(x) 
    print "x is true";

As opposed to

if (x) { print "x is true"; }
if(x) {
    print "x is true";    
}

If you format your single statement ifs without brackets or know a programmer that does, what led you/them to adopt this style in the first place? I'm specifically interested in what benefits this has brought you.

Update: As the most popular answer ignores the actual question (even if it presents the most sane advice), here's a roundup of the bracket-less pros.

  1. Compactness
  2. More readable to some
  3. Brackets invoke scope, which has a theoretical overhead in some cases
6
  • You can't follow up "this isn't which is better" with "what are the pros". They're both comparisons. Sep 18, 2008 at 22:10
  • Pros are arguments for, cons are arguments against. Every decision has pros or cons. "Better" is a judgment call where you decide which pros and cons are more suited to your particular situation. Sep 18, 2008 at 22:23
  • Isn't this one of the questions explicitly "forbidden" by Jeff at one time? What can anyone possibly gain from reading this?
    – Tim Frey
    Sep 30, 2008 at 20:19
  • 3
    For a question labelled 'c', it is surprising to see non-C notations such as 'print "x is true";' Jul 10, 2009 at 5:36
  • @Jonathan it's just pseudo code. I tagged the question c because, in my experience, c coders tend to use the bracket-less short form more often than not and I wanted their perspective on the issue. Jul 10, 2009 at 7:28

42 Answers 42

52

I find this:

if( true ) {
    DoSomething();
} else {
    DoSomethingElse();
}

better than this:

if( true )
    DoSomething();
else
    DoSomethingElse();

This way, if I (or someone else) comes back to this code later to add more code to one of the branches, I won't have to worry about forgetting to surround the code in braces. Our eyes will visually see the indenting as clues to what we're trying to do, but most languages won't.

5
  • Also, if 'DoSomething' happens to a multi-line macro you can run into problems.
    – Trent
    Sep 18, 2008 at 23:16
  • 1
    I also like the convention of starting and ending all if statements with brackets, even if it only contains 1 command... By the way the reason why this 'feature' was introduced was (probably) because back in the early days of programming, it was desired to have to type as little as possible...
    – sven
    Sep 30, 2008 at 20:15
  • I agree, but less important these days when auto-formatting editors like Eclipse and NetBeans will fix your indenting for you which will tell you right away that something is wrong (assuming you hit the "fix code" key sequence often.)
    – Bill K
    Jan 14, 2009 at 18:08
  • 18
    I prefer the second block. All the brackets just tangle up the code and make it easy to spot the error if you bung them up. I've been "braketless" if statement approach for years and have never had the problem of forgetting to add brackets when adding a new line.
    – priestc
    Jul 10, 2009 at 4:58
  • I use brackets everywhere so the code is uniform and more readable to me ... in alternative I don't dislike the form (true) ? dosomething() : dosomethingelse()
    – WonderLand
    Aug 23, 2017 at 9:39
48

I strongly dislike any style that places the if's test and body on the same line.

This is because sharing the line makes it impossible to set a breakpoint on the if's body in many debuggers because breakpoints are typically line number based.

6
  • 1
    I agree, but tons of programmers seem to disagree. They must have their reasons. Sep 18, 2008 at 22:44
  • Visual Studio 2008 (2005?) is able to debug per statement, not per line.
    – spoulson
    Sep 19, 2008 at 1:21
  • What about "if (blah) { return; }"? Seems pretty harmless to me, even if you're trying to set a breakpoint there.
    – Parappa
    Sep 19, 2008 at 1:52
  • 1
    Yeah, but if you split up every if-statement in test and instruction on separate lines, then you should do so for if-x-return statemnts, for the sake of consistenncy. Sep 19, 2008 at 6:59
  • 1
    There are always exceptions (talk about a logic knot...) "A foolish consistency is the hobgoblin of little minds." Sep 19, 2008 at 19:06
34

Always using braces is a good idea but the standard answer that's always given "what if somebody adds a line of code and forgets to add the braces?" is a rather weak reason.

There is a subtle bug which can be introduced by not having the braces from the start. It's happened to me a few times and I've seen it happen to other programmers.

It starts out, innocently enough, with a simple if statement.

if (condition)
    do_something();
else
    do_something_else();

Which is all well and good.

Then someone comes along and adds another condition to the if. They can't add it using && to the if statement itself because the logic would be incorrect, so they add another if. We now have:

if (condition)
    if (condition2)
        do_something();
else
    do_something_else();

Do you see the problem? It may look right but the compiler sees it differently. It sees it like this:

if (condition)
    if (condition2)
        do_something();
    else
        do_something_else();

Which means something completely different. The compiler doesn't care about formatting. The else goes with the nearest if. Humans, on the other hand, rely on formatting and can easily miss the problem.

2
  • Good thinking - I guess that's one of the advantages of something like Python where indentation does have syntactical value. Sep 20, 2008 at 13:45
  • 3
    ps... NEVER nest ifs without adding braces if they aren't already there. The concept that someone might do what the author said hurts my soul.
    – Bill K
    Jan 14, 2009 at 18:11
21

I always use

if(x) 
{
    print "x is true";    
}

leaving out the braces can result in someone maintaining the code mistakenly thinking they are adding to the if clause if they add a line after the current line.

2
  • 2
    Aside: Which is why I also like Python's indention awareness. You're going to indent anyway, might as well make it mean something. This argument only occurs in languages that make blocking characters ({ } in this case) optional/conditional. Sep 19, 2008 at 4:06
  • I agree with Ferruccio (stackoverflow.com/questions/97506/formatting-of-if-statements/…) that your argument is pretty weak. This is such an easy mistake to make that it's also drilled into the heads of new programmers to the point where they (at least, I) recognize and correct it unconsciously.
    – Chris Lutz
    Jul 10, 2009 at 5:27
14

I use

if (x)
{
    DoSomething();
}

for multiple lines, but I prefer bracketless one liners:

if (x)
   DoSomething();
else
   DoSomethingElse();

I find the extraneous brackets visually offensive, and I've never made one of the above-mentioned mistakes not adding brackets when adding another statement.

3
  • 4
    +1. It seems the main argument people seem to have against bracket-less if statements is fear that they'll forget to add the brackets when adding a new line of code. Yet I've never heard any real world instances of someone having a problem with doing that. I've been "bracket-less" pretty much since I started programming and have never had a problem forgetting to add the brackets.
    – priestc
    Jul 10, 2009 at 5:03
  • 1
    +1 - I agree that one-liner if()s are perfectly okay. Anyone adding to your code should be experienced enough to know that they have to add brackets if they add more lines. Anyone who doesn't know at least that much will not be working anywhere near my code.
    – Chris Lutz
    Jul 10, 2009 at 5:32
  • I wish people would stop writing code for themselves and start writing code for the person who comes after them. What will they be like? No idea. But if you put braces you're reducing that person's risk. It doesn't matter that you're not at risk. It's the person who comes after you. Apr 1, 2012 at 11:40
8
if
{
// code
}
else 
{
// else code
}

because i like when blocks of code line up (including their braces).

2
  • 2
    That's terrorism against code aesthetics! I wouldn't want to work with that code.
    – piotr
    Jul 10, 2009 at 5:10
  • 1
    If the comments (code) were indented, this is the form I find most legible. If the code inside the braces was not indented, then it is horrid. I usually don't put the braces in place unless there are several statements in the block - but I don't mind when they are inserted uniformly. Jul 10, 2009 at 5:40
7

If I code:

if(x) 
    print "x is true";

and 6 months later need to add a new line, the presence of curly braces makes it much less likely that I'll type

if(x) 
    print "x is true";
    print "x is still true";

which would result in a logical error, versus:

if(x) { 
    print "x is true";
    print "x is still true";
}

So curly braces make such logical errors easier to read and avoid, I find.

1
  • THIS. A million times: THIS. Sep 18, 2008 at 22:23
7

Like Matt (3 above), I prefer:

if (x)
{
    ...statement1
    ...statement2
}

and

if (x)
    ...statement
else
    ...statement

I think its pretty strange to think that someone may come along later and NOT realise they have to add the braces to form a multi-line if block. If that's beyond their capabilities, I wonder what other things are!

5

Single statement if blocks lacking braces:

Pros:

  • fewer characters
  • cleaner look

Cons:

  • uniformity: not all if blocks look the same
  • potential for bugs when adding statements to the block: a user may forget to add the braces and the new statement would no be covered by the if.

As in:

if(x) 
    print "x is true";
    print "something else";
5

I tend only to single line when I'm testing for break conditions at the beginning of a function, because I like to keep this code as simple and uncluttered as possible

public void MyFunction(object param)
{
     if (param == null) return;

     ...
}

Also, if I find I do want to avoid braces and inline an if clause code, I may single line them, just so it is obvious to anyone adding new lines to the if that brackets do need to be added

4

I use

if (cond) {
  ...
} else {
  ...
}
  • Everything should always have braces. Even if now I only have one line in the if block, I made add more later.
  • I don't put the braces on their own lines because it's pointless waste of space.
  • I rarely put the block on the same line as the conditional for readability.
4

Joel Spolsky wrote a good article: Making Wrong Code Look Wrong

He specifically addresses this issue…

if (i != 0)  
    foo(i);

In this case the code is 100% correct; it conforms to most coding conventions and there’s nothing wrong with it, but the fact that the single-statement body of the ifstatement is not enclosed in braces may be bugging you, because you might be thinking in the back of your head, gosh, somebody might insert another line of code there

if (i != 0)
    bar(i);
    foo(i);

… and forget to add the braces, and thus accidentally make foo(i)unconditional! So when you see blocks of code that aren’t in braces, you might sense just a tiny, wee, soupçon of uncleanliness which makes you uneasy.

He suggests that you…

… deliberately architect your code in such a way that your nose for uncleanliness makes your code more likely to be correct.

1
  • 4
    I find this argment non-compelling. I always have. Jul 10, 2009 at 5:41
4

I dislike using braces when they're not required. I feel like it bloats the number of lines in a method and makes it unreadable. So I almost always go for the following:

if (x)
   print "x is true"
for (int i=0; i<10; i++)
   print "y is true"

And so forth. If someone needs to add another statement then he can just add the braces. Even if you don't have R# or something similar it is a very small deal.

Still, there are some cases that I would use braces even if there is only one line in the statement, and that is if the line is especially long, or if I need comments inside the that 'if'. Basically, I just use whatever seems nicer to my eyes to look at.

3

Whitespace is your friend ....

but, then again, I like:

if (foo)
{
    Console.WriteLine("Foobar");
}
3

Seriously, when's the last time you had a bug in any code anywhere that was cause someone did:

if (a)
  foo();
  bar();

Yeah, never...* The only real 'pro' here is to just match the style of the surrounding code and leave the aesthetic battles to the kids that just got outta college.

*(caveat being when foo(); bar(); was a macro expansion, but that's a problem w/ macros, not curly braces w/ ifs.)

5
  • Not a lot, but I have seen it
    – johnc
    Sep 18, 2008 at 23:14
  • I've done it more than once. In one case, a beta version of a bot I was writing had a rather nasty security bug because of the lack of braces.
    – epochwolf
    Sep 19, 2008 at 0:17
  • yep, I've seen that happen too.
    – nickf
    Sep 19, 2008 at 5:57
  • I've never had a bug because of that... ...because I'm smart enough to always use braces so it can't happen. If you don't...it will.
    – Cody Hatch
    Sep 19, 2008 at 6:00
  • Visual Studio would correct the misleading format with it's auto format feature (not sure if other IDE's have similar features). Still the only time I really leave out the brackets is when my if condition either returns, breaks, or throws an exception.
    – ebrown
    May 22, 2009 at 19:20
3
if (x) {
    print "x is true";    
}
else {
    do something else;
}

I always type braces. It's just a good habit. Compared to thinking, typing is not "work".

Note the space before the conditional. That helps it look not like a method call.

2
if (x)
{
    print "x is true";
}

Opening and closing brace in same column makes it easy to find mismatched braces, and visually isolates the block. Opening brace in same column as "if" makes it easy to see that the block is part of a conditional. The extra white space around the block created by the rows containing just braces makes it easy to pick it out the logical structure when skimreading code. Always explicitly using braces helps avoid problems when people edit the code later and misread which statements are part of the conditional and which are not - indentation may not match reality, but being enclosed in braces always will.

2

About the only time no-bracing seems to be accepted is when parameter checking variables at the start of a method:

public int IndexOf(string haystack, string needle)
{
    // check parameters.
    if (haystack == null)
        throw new ArgumentNullException("haystack");
    if (string.IsNullOrEmpty(needle))
        return -1;

    // rest of method here ...

The only benefit is compactness. The programmer doesn't have to wade throught un-necessary {}'s when it's quite obvious that:

  • the method exits on any true branch
  • it's fairly obvious these are all 1-liners

That said, I would always {} for program logic for the reasons stated by others. When you drop the braces it's too easy to mentally brace when it's not there and introduce subtle code defects.

1
  • s/throught/through/  (I can’t suggest a one-character edit, and I don’t see any other changes worth making.) BTW, cute code example. Aug 22, 2017 at 21:33
2

Other way would be to write:

(a==b) ? printf("yup true") : printf("nop false");

This will be practical if you want to store a value comparing a simple condition, like so:

int x = (a==b) ? printf("yup true") : printf("nop false");
1
  • While correct, the question is asking for the benefits of different styles, not how to accomplish it in different ways. Generally the differences are in readability and ternary operators aren't overly readable.
    – user1393215
    Mar 4, 2015 at 20:03
2

H8ers be damned I'm not really one for dogmatic rules. In certain situations, I'll actually favor compactness if it doesn't run over a certain width, for example:

if(x > y)      { xIsGreaterThanY(); }
else if(y > x) { yIsGreaterThanX; }
else           { xEqualsY(); }

This is far more readable to me than:

if( x > y ){
    xIsGreaterThanY(); 
}else if( x < y){
    yIsGreaterThanX();
}else{
    xEqualsY();
}

This has the added benefit of encouraging people to abstract logic into methods (as i've done) rather than keep lumping more logic into nested if-else blocks. It also takes up three lines rather than seven, which might make it possible to not have to scroll to see multiple methods, or other code.

1

I prefer the bracketed style, mainly because it gives the eyes a clear start and stop point. It makes it easier to see what is actually contained in the statement, and that it actually is an if statement. A small thing, perhaps, but that's why I use it.

1

so long as it is consistent amongst the team you work in then it doesnt matter too much

that everyone does the same is the main thing

1
  • See, I disagree with the "as long as you're consistent" rule. There are certain styles that can help you eliminate errors from your programming, and most programmers are human beings who will occasionally be inconsistent in their style. Sep 18, 2008 at 22:46
1

Bracketing your one-liner if statements has the considerable sane-making advantage of protecting you from headaches if, at some later point, you (or other coders maintaining or altering your code) need to add statements to some part of that conditional block.

1

If you do something like this:

if(x)
{
    somecode;
}
else
{
    morecode;
}

This works out better for source control and preprocessor directives on code that lives a long time. It's easier to add a #if or so without inadvertently breaking the statement or having to add extra lines.

it's a little strange to get used to, but works out quite well after a while.

1
  • (1) I don’t understand what this has to do with adding preprocessor directives like #if — can you explain that?  (2) I believe that I sort-of understand what you’re saying about source control, but it’s not entirely clear and could also benefit from more explanation.  (3) Why do you say that this is “a little strange to get used to”? It’s what many people were taught, and anybody with any experience programming in the real world will have seen code like this; it’s not like it’s something nouveau or bizarre. Aug 22, 2017 at 21:18
1

If it's one line of if (and optionally one line of else) I prefer to not use the brackets. It's more readable and concise. I say that I prefer it because it is purely a matter of preference. Though I think that trying to enforce a standard that you must always use the braces is kind of silly.

If you have to worry about someone adding another line to the body of the if statement and not adding the (only then required) braces, I think you have bigger problems than sub-byzantine coding standards.

1
  • I wish I could give this more than one upvote - this sums up how I feel exactly. Jul 10, 2009 at 5:34
1
/* I type one liners with brackets like this */
if(0){return(0);}
/* If else blocks like this */
if(0){
    return(0);
}else{
    return(-1);
}

I never use superfluous whitespace beyond tabs, but always including the brackets saves heaps of time.

1
  • 1
    I wouldn't consider adding a space between the "if" and its bracket as "superfluous". I bet you're one of those people who write "if(x=1){x=y+z;}" I find that one of the most hard-to-read coding styles there is...
    – nickf
    Sep 19, 2008 at 5:59
1

I dislike closing braces on the same line with the follow keyword:

if (x) {
    print "x is true";    
} else {
    do something else;
}

This makes it harder to remove/comment-out just the else clause. By putting the follow keyword on the next line, I can take advantage of, for example, editors that let me select a range of lines, and comment/uncomment them all at once.

if (x) {
    print "x is true";    
}
//else {
//    do something else;
//}
1

I always prefer this:

if (x) doSomething();

if (x) {
    doSomthing();
    doOtherthing();
}

But always depend on the language and the actions you're doing. Sometimes i like to put braces and sometimes not. Depend on the code, but i coding like a have to write once, re-write ten times, and read one hundred times; so, just do it like you want to and like you want to read and understand more quickly

1

No matter what, this is the way I go! It looks the best.

If(x)
{
    print "Hello World !!"
}
Else
{
    print "Good bye!!"
}
1

If you're curious what the names for the various code formatting styles are, Wikipedia has an article on Indent Styles.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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