Is it a bad practice to use an if-statement without curly braces? [closed]
Asked Answered
C

15

182

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?

Complexion answered 23/1, 2010 at 22:59 Comment(3)
possible duplicate of Why is it considered a bad practice to omit curly braces?Morphogenesis
In my opinion it's bad, because you start relying on whitespace indentation which is almost never fully consistent. It derails the reader's train of thought when they have to worry about such things.Ange
It's a good practice to use it > blog.codecentric.de/en/2014/02/curly-bracesPostobit
S
283

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

Showdown answered 23/1, 2010 at 23:2 Comment(19)
And you should always code for maintainability. After all, I'm pretty sure the compiler doesn't care which form you use. Your coworkers, however may be pist if you introduce a bug because of a silly curly brace error.Rheometer
Or you could use a language that doesn't use brackets for code blocks...Tuscany
@Tor Valamo: Pascal uses begin/end instead of curly braces and you can run into exactly the same problems. I assume you really mean languages in which you have to explicitly close if statements with something like an end if.Ingenerate
@Ingenerate - No, I mean like python. Because I'm chauvinistic in this regard.Tuscany
I disagree, when you need to add code you add the brackets. It is fairly simple to read and implement.Windup
Luc: Sure, it's simple, but it's also easy to forget, and if you do forget, it's maddening and hard to debug. Is saving a few characters really worth the potential headaches? Most of us seem to agree the answer is "no."Showdown
Further proof mistakes can (and do) happen: imperialviolet.org/2014/02/22/applebug.htmlAmsterdam
Claiming that the SSL bug is an argument in favor of braces is disingenuous. It is not as if the developer intended to write if (…) { goto L; goto L; } but forgot the braces. It is purely coincidental that ``if (…) { goto L; goto L; }` happens not to be a security bug, because it is still a bug (just not one with security consequences). On another example, things could go in the opposite direction and the braceless code could be accidentally safe. On a third example, the braceless code would be bug-free initially and the developer would introduce a typo while adding the braces.Clog
Pascal: What a shame if the code would have been accidentally safe, despite a programming error! If you always use the braces, there can't be any accidents when "adding" them.Showdown
The author of the article talking about the Apple bug concludes that "Maybe the coding style contributed to this by allowing ifs without braces, but one can have incorrect indentation with braces too, so that doesn't seem terribly convincing to me". I agree.Bibbie
Adding a second statement to the if clause will result in a compilation error.Nealey
@Showdown I know it's a 3 years old thread, but I stumbled upon this thread and couldn't help but to read your comment about adding a brace is "easy" to forget. It isn't easy to forget because if you use the proper tools to write your code, such tools add those brackets for you. Even if you don't use the proper tool, if you happen to be using a language that uses braces (I love python as much as you do, though) it should be in your muscle memory when writing an if statement, and if it isn't, then you should be working on that.Castrate
@ILikeBeansTacos And in the grand tradition of kicking a dead horse… great tools can definitely help, but not everybody uses them. There are lots of ways that C lets you shoot yourself in the foot, and I consider this to be one of them. Just because the language LETS you do something (like omit braces from if/else statements) doesn't mean it's a good idea. (Also, I do not love Python.)Showdown
if-else is a single statement not multiple statements.Rachmaninoff
I know it's old but... In the case given of if() .. else ... then if you added a second statement after the line for the if you'd get a compile error not some subtle logic bug - if () line1 line2 else line3 would fail because there would be no matching if for the else statement.Advection
Sure, @Peter, in that specific case (when you have an if and an else) then that's true. But if you ever use an if without an else, the compiler will not help you. And if your extra line of code comes after the single-line else body, the compiler will not catch it there, either.Showdown
@Showdown I can't speak for all tools, but in VS the Apple bug would have been hard to miss. Not only will unreachable code generate a warning, but it's also grayed out for a visual cue.Ogilvie
a lot of times you can get away with using a ternary operatorObelia
if we are talking about speed , will there be any different between the two syntaxes?Blondell
C
151

One problem with leaving out statement blocks is the else-ambiguity. That is C-inspired languages ignore indentation and so have no way of separating this:

if(one)
    if(two)
        foo();
    else
        bar();

From this:

if(one)
    if(two)
        foo();
else
    bar();
Contraceptive answered 23/1, 2010 at 23:33 Comment(5)
This is a far more serious problem than the one mentioned in the top answer (adding a second statement).Ribbonfish
indeed, this answer actually took me from reading these answers cynically to being mildly concerned i may have actually made this mistake.Inshrine
If anyone else was wondering like I was which way C actually interprets it, a test I did with GCC interprets this code in the first way. tpcg.io/NIYeqxIndoeuropean
"ambiguity" is the wrong term. There is no ambiguity whatsoever in how the parser will see this: the else binds greedily to the nearest, innermost if. The problem arises where C or similar languages are being coded by people who don't know this, don't think about it, or didn't have enough coffee yet - so they write code that they think will do one thing, but the language spec says the parser has to do something else, which might be very different. And yes, that's another rock-solid argument in favour of always including braces even if the grammar flags them as theoretically 'unnecessary'.Acrodont
From what I have seen (the "dangling else problem") the human-readable grammar is ambiguous, but either the parser defaults to the mentioned option, or the grammar is rewritten to be less readable, but unambiguous.Bracknell
V
46

My general pattern is that if it fits on one line, I'll do:

if(true) do_something();

If there's an else clause, or if the code I want to execute on true is of significant length, braces all the way:

if(true) {
    do_something_and_pass_arguments_to_it(argument1, argument2, argument3);
}

if(false) {
    do_something();
} else {
    do_something_else();
}

Ultimately, it comes down to a subjective issue of style and readability. The general programming world, however, pretty much splits into two parties (for languages that use braces): either use them all the time without exception, or use them all the time with exception. I'm part of the latter group.

Vincentia answered 23/1, 2010 at 23:3 Comment(5)
Although, as easy as it is to write if(true){ do_something(); }, why take the chance on having another programmer introduce a serious bug down the road (lookup Apple's "goto fail" total ssl code screwup).Purulent
No amount of brackets will free the maintainer from using his brain. I support the idea of "no brackets if it fits in one line" because, well, for me such an if is just a version of the ternary if operator where one doesn't need to do anything in the "after :" part of ternary. And why would anyone introduce brackets to ternary if?Varner
I don't agree at all that ultimately it is subjective, nor that it only affects style and readability. As someone who has wasted time trying to debug issues that it turned out were caused by missing block delimiters (and not noticing their absence), because I had to use a coding style that omits them when 'unnecessary' - and who has read about numerous terrible bugs very arguably caused by such coding styles - I think this is a very objective, practical issue. Sure, with a style mandating delimiters, we can still forget them, but surely - at least - muscle memory makes us far less likely to.Acrodont
Just wait until a prettifier is applied and your 1-liner is a 2-liner. Just use the braces.Waldack
This is our practice - either all on one line or use braces.Latchkey
D
15

The "rule" I follow is this:

If the "if" statement is testing in order to do something (I.E. call functions, configure variables etc.), use braces.

if($test)
{
    doSomething();
}

This is because I feel you need to make it clear what functions are being called and where the flow of the program is going, under what conditions. Having the programmer understand exactly what functions are called and what variables are set in this condition is important to helping them understand exactly what your program is doing.

If the "if" statement is testing in order to stop doing something (I.E. flow control within a loop or function), use a single line.

if($test) continue;
if($test) break;
if($test) return;

In this case, what's important to the programmer is discovering quickly what the exceptional cases are where you don't want the code to run, and that is all coverred in $test, not in the execution block.

Dreamland answered 10/2, 2014 at 8:8 Comment(0)
V
11

I am using the code formatter of the IDE I use. That might differ, but it can be setup in the Preferences/Options.

I like this one:

if (statement)
{
    // comment to denote in words the case
    do this;
    // keep this block simple, if more than 10-15 lines needed, I add a function for it
}
else
{
    do this;
}
Viv answered 23/1, 2010 at 23:2 Comment(8)
This being an entirely subjective style issue, I personally don't like the redundancy of the brace-only lines. But hey.Vincentia
I support this style. Most people read code from left to right and it sort of makes our eyes anchored to left edge of screen. It helps to visually separate and extract code to logical blocks of steps.Spaceman
I've always preferred this style. Much easier to find the corresponding closing parenthesis. So it takes a lot of space ? Use a smaller font.Fustanella
I'm with mloskot and timday - I've always found that embedding the braces (essentially 'control' characters) in the rest of the code makes code harder to read. Splitting them out on separate lines helps make the logical blocks more distinct.Joyless
This is the only style I consider readable.Gassaway
I always find it easier to "scan" through code when the braces are on separate lines. That goes for everything; classes, methods, if- and while-statements, et cetera. Never liked having that first brace on the same line...Rattoon
Whitespace is cheap, especially when you have a code folding capable IDE.Trawler
i know this is late, but @Svish, gotta be careful about return statements and javascript :), all the sudden curly braces are required to be on the same lineTetrapod
H
9

Having the braces right from the first moment should help to prevent you from ever having to debug this:

if (statement)
     do this;
else
     do this;
     do that;
Hackman answered 23/1, 2010 at 23:4 Comment(3)
That seems to be the accepted rationale, but (to play devil's advocate here) wouldn't a single additional syntax-highlighting rule also solve this, while saving one line?Centime
So will having an IDE that corrects the indentation when you hit ; :)Permian
Why would a programmer who knows C don't notice, that there is no } after the second do that? The missing brace would trigger me immediately. Only a Python dev could fall for this one. If code in C is intended with no sign of new scope, it is not forming a new scope, it is usually used to signal a continuation of the line above, even if that line above is else.Hubris
H
7

Use braces for all if statements even the simple ones. Or, rewrite a simple if statement to use the ternary operator:

if (someFlag) {
 someVar= 'someVal1';
} else {
 someVar= 'someVal2';
}

Looks much nicer like this:

someVar= someFlag ? 'someVal1' : 'someVal2';

But only use the ternary operator if you are absolutely sure there's nothing else that needs to go in the if/else blocks!

Hyperthermia answered 23/1, 2010 at 23:18 Comment(0)
P
4

I prefer using braces. Adding braces makes it easier to read and modify.

Here are some links for the use of braces:

Peripeteia answered 23/1, 2010 at 23:21 Comment(0)
S
3

From my experience the only (very) slight advantage of the first form is code readability, the second form adds "noise".

But with modern IDEs and code autogeneration (or autocompletion) I strongly recommend using the second form, you won't spend extra time typing curly braces and you'll avoid some of the most frequent bugs.

There are enough energy consuming bugs, people just shoudn't open doors for big wastes of time.

One of the most important rule to remember when writing code is consistency. Every line of code should be written the same way, no matter who wrote it. Being rigorous prevents bugs from "happening" ;)

This is the same with naming clearly & explicitly your variables, methods, files or with correctly indenting them...

When my students accept this fact, they stop fighting against their own sourcecode and they start to see coding as a really interesting, stimulating and creative activity. They challenge their minds, not their nerves !

Secundine answered 24/1, 2010 at 0:9 Comment(0)
N
2

It is a matter of preference. I personally use both styles, if I am reasonably sure that I won't need to add anymore statements, I use the first style, but if that is possible, I use the second. Since you cannot add anymore statements to the first style, I have heard some people recommend against using it. However, the second method does incur an additional line of code and if you (or your project) uses this kind of coding style, the first method is very much preferred for simple if statements:

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

However, I think the best solution to this problem is in Python. With the whitespace-based block structure, you don't have two different methods of creating an if statement: you only have one:

if statement:
    do this
else:
    do this

While that does have the "issue" that you can't use the braces at all, you do gain the benefit that it is no more lines that the first style and it has the power to add more statements.

Nevanevada answered 23/1, 2010 at 23:5 Comment(1)
I by myself think the way how Python handles if-else statements is very ugly, but then again, I'm no Python programmer (yet)Vasyuta
B
2

Personally I use the first style only throw an exception or return from a method prematurely. Like argument Checking at the beginning of a function, because in these cases, rarely do I have have more than one thing to do, and there is never an else.

Example:

if (argument == null)
    throw new ArgumentNullException("argument");

if (argument < 0)
    return false;

Otherwise I use the second style.

Bulbul answered 23/1, 2010 at 23:19 Comment(0)
G
1

I have always tried to make my code standard and look as close to the same as possible. This makes it easier for others to read it when they are in charge of updating it. If you do your first example and add a line to it in the middle it will fail.

Won't work:

if(statement) do this; and this; else do this;

Galleywest answered 23/1, 2010 at 23:2 Comment(0)
M
1

My personal preference is using a mixture of whitespace and brackets like this:

if( statement ) {

    // let's do this

} else {

    // well that sucks

}

I think this looks clean and makes my code very easy to read and most importantly - debug.

Medlar answered 24/1, 2010 at 2:51 Comment(0)
B
0

I agree with most answers in the fact that it is better to be explicit in your code and use braces. Personally I would adopt a set of coding standards and ensure that everyone on the team knows them and conforms. Where I work we use coding standards published by IDesign.net for .NET projects.

Bobbysoxer answered 23/1, 2010 at 23:13 Comment(0)
I
0

I prefer putting a curly brace. But sometimes, ternary operator helps.

In stead of :

int x = 0;
if (condition) {
    x = 30;
} else {
    x = 10;
}

One should simply do : int x = condition ? 30 : 20;

Also imagine a case :

if (condition)
    x = 30;
else if (condition1)
    x = 10;
else if (condition2)
    x = 20;

It would be much better if you put the curly brace in.

Inseverable answered 29/1, 2010 at 8:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.