Question

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
Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

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.

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.

if
{
// code
}
else 
{
// else code
}

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

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.

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!

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";

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

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.

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.

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.

Whitespace is your friend ....

but, then again, I like:

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

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.)

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.

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");
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.

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.

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.

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.

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

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.

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.

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.

/* 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.

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;
//}

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

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top