It’s all a matter of style


Probably one of the most religious issues for developers (at least those using the
same platform and programming language) is bracing style.  There are several
styles available, with the two most popular being K&R style & Allman style. 
I found this nice description on the different indent styles here,
and pasted the different indentation styles below:

‘K&R style’ — Named after Kernighan & Ritchie, because
the examples
in K&R are formatted this way. Also called `kernel style’ because the
Unix kernel is written in it, and the `One True Brace Style’ (abbrev.
1TBS) by its partisans. In C code, the body is typically indented by
eight spaces (or one tab) per level, as shown here. Four spaces are
occasionally seen in C, but in C++ and Java four tends to be the rule
rather than the exception.
 

if () {  
   

‘Allman style’ — Named for Eric Allman, a Berkeley hacker who wrote
a
lot of the BSD utilities in it (it is sometimes called `BSD style’).
Resembles normal indent style in Pascal and Algol. It is the only style
other than K&R in widespread use among Java programmers. Basic indent per level
shown here is eight spaces, but four (or sometimes three)
spaces are generally preferred by C++ and Java programmers.
 

if ()
{           
 
‘Whitesmiths style’ — popularized by the examples that came with
Whitesmiths C, an early commercial C compiler. Basic indent per level
shown here is eight spaces, but four spaces are occasionally seen.
 

if ()
        {            
   

‘GNU style’ — Used throughout GNU EMACS and the Free Software
Foundation code, and just about nowhere else. Indents are always four
spaces per level, with `{‘ and `’ halfway between the outer and inner
indent levels.
 

if ()
  {

My “religious” preference is definitely Allman style, but from what I understand
authors tend to prefer K&R so that they don’t lose precious book space when printing
source.  The cool thing is that Whidbey lets you format your code and use whatever
indentation style you prefer (there’s 60+ other choices you can make to format your
code).  What style do you use, and are you religious about it?  Say you
found a sample on a web site that used a different bracing style, would you change
the bracing style before running the app? I would, but only if I were planning on
keeping the code…

Comments (44)

  1. Kent says:

    Definitely Allman style

  2. Catatonic says:

    I find Allman code easiest to read & to write, but it’s no big deal. I care more about tabs. Use an editor that doesn’t convert them to spaces, so I can be happy with my 2-space tabs and you can keep your great big ones.

  3. David Nicholson says:

    Well the beauty of VS is that when I type a } it makes everything ‘right’, so most stuff tends to get formatted before running.

    And of course Allman style is the only way to write ;).

  4. My current preference is Allman style, but I used to be a K&R guy. Even back when I was doing Delphi I used to write "if (…) then begin" all on one line, all in the name of saving space. Screen real-estate has improved a lot through in recent years so now I prefer the readability advantage of Allman over the space-savings of K&R.
    While I’m not religious about it, I do feel that it’s very imporant when doing team development that everyone agrees on the same style – nothing worse than looking at code that has a mix of two or more different styles used interchangeably.

  5. Big tabs are another pet peeve of mine, if you code inside a namespace, and then you have a class with a method and that method has nested logic, you’re talking about four tabs for code, not very pretty…

    I definitely agree with Luke that mixing and matching styles is a big no-no…

  6. Kevin Daly says:

    Definitely Allman for me too.
    And I admit that if I pick up code formatted in K&R style that I’m intending to keep/extend, I do reformat it, even though in my heart of hearts I know it’s silly and anal-retentive to do so.
    I’m curious as to how I developed this preference (I honestly don’t remember, and my introduction to C was the Kernighan and Ritchie book back in my Amiga days). I always format HTML open/close tags to be balanced and symmetrical in the same way, so either one preference influenced the other or possibly they’re both evidence of a deeper pathology.
    Gosh.

  7. Bob Banks says:

    Okay, I’ll go against the grain. K&R for me. Don’t really like having a brace on a line by itself. I also always put in my closing brace immediately after the opening brace. Also changed VS.NET settings so that it doesn’t automatically move the brace to a new line.

  8. Juan Murillo says:

    Check out the java coding conventions, this is the true way to indent if you want other to have a good time reading your code:

    http://java.sun.com/docs/codeconv/html/CodeConventions.doc3.html#262

  9. Keith Patrick says:

    I use K&R and am *extremely* anal about using it, too. And another thing I’m pretty bad about is going through and replacing other people’s:
    if (x == y)
    x = null;
    else
    x = y;

    with:
    if (x == y) {
    x = null;
    }
    else {
    x = y;
    }

  10. It’s K&R or Java for me too. The brackets just shouldn’t have a line of their own.
    if (condition) {
    statements;
    } else if (condition) {
    statements;
    } else {
    statements;
    }

    In truth, if you were creating a language today and you weren’t trying to recruit C programmers to it, you wouldn’t have the brackets at all – VB’s like that. The main use for the braces is for bragging rights: C/C++/Java have them and VB/COBOL/APL don’t.

  11. Mike says:

    /*
    *There is a lot of things VB dosn’t have.
    */

    Read the source of Linux which employs the K&R format. The code is easy to read and it is structured nicely. The largest collaborative project in the world uses it, there is no more to say.

  12. I’m a K&R guy, but I’m slowly converting to Allman’s. Each new line used to be pain for me, but the readability is worth it.

  13. C Ma says:

    I like to use the Horstmann style, which has the advantage of space saving like the K&R style but the readability of the Allman style. After the opening brace, press tab and start typing up the code. If I found a piece of code that I would use in my programs that used a different style, I would probably go ahead and change it, just to be consistent.

  14. K&R style is a abomination that should be stricken

    from the face of the planet. :-)

    Allman style is the only way to go, IMNSHO.

  15. Flinky Wisty Pomm says:

    Infidels!

    Those unfortunates who end up in my employ or training room use K&R or find themselves on the wide end of the LART.

    I’ve never understood why Allman style is thought more readable than the One True Brace Style, it’s ugly, and it’s illogical. /Statements/ get a line to themselves (with minor caveats), braces do not.

    That said, I have to agree with the other K&R fan who thinks braces should be dropped entirely. Kudos: but only if you’re going to replace them with strict indentation like Python which is cruftless, reaadable /and/ logical. Huzzah!

  16. Greg Woods says:

    I program full-time on a 1024×768 laptop screen. Subtract bare minimum VS.NET toolbars etc. You’re left with an area that’s pefectly usable…. if you use K&R.

    I can’t understand this readability argument. Your eyes scan down the column that the ‘if’, ‘select’ ‘for’ line starts on, and look for the matching closing brace. I never have to look for the opening brace because it’s instinctive for me to type: if(){ then go and fil in the condition.

    ong live K&R. I want to see code on my page not needless white space!

  17. Dave says:

    I apparently use ‘Whitesmith’s’. I find it interesting that style guides say that Allman and Whitesmith’s are equal in prevalence as I have come across no-one else who uses the same style as me and have suffered much chastising about it — I do see Allman’s a great deal, though.

    Long live Whitesmith’s and all the (evidently hidden) masses who use it.

    BTW, I do have to agree with Keith Patrick’s comments about single-statement bodies. I break my own style by allowing opening and closing braces to be on one line in those cases but I’d much rather have the braces than not. I’ve been bitten in the ass a couple times by inferring meaning from misapplied indent (‘misapplied’ meaning from the standpoint of the original code’s own style, not my preferred style; this is of course why Python is preposterous).

  18. Jack Black says:

    Allman style for me too. I think statements like "Braces should not get their own line, only statements" are stupid – for one, braces ARE statements, in a way (think Pascal begin and end). For two, your ending braces get a line to themselves in 1TBS, don’t they?

  19. Eric says:

    Allman for almost everything, with K&R for the few pieces of code where Allman is not appropriate (long series of if/else, independant if followed by just a continue/break or goto (yes those can be useful C or C++ but almost never in more modern languages).

    And indeed there even even a few occasions where a single line if () { … } is appriate. That’s why you must not be too religious. Strict, yes. Stuborn, no.

  20. tom says:

    Allman style. It is a lot easier to read if the braces line up vertically; makes it clearer what a block is.

    i.e. you have an if, while etc. on one line, and the block that it executes on the following line. Block is made up of brace, statements, close brace…

    I’m also rather anal about ALWAYS putting braces around even single-line blocks in the interests of readability.

  21. ChronoFish says:

    I hate religious arguments about programming style – yet I’m so opinionated that I can’t help to comment and get sucked in to the discussion:

    I used to be a strict K&R but have really honed in on Allman in the last two years or so. Allman with inline acceptions (begin-end braces on one line – as long as they do not contain nested braces)

    I think I like K&R at the time because of the saving in screen realestate. But now that I’m not limited to an 80×25 CRT display Allman really does make more sense. When you have multiple nestings of {} it helps a great deal to have them in the same column. It also flows well logically – Some block label as the header, and then the code-block:

    block-label

    {



    }

    Indentations are a must – but must not be over done. Again I find inline acceptable:

    block-label { …. }

    But never

    block-label {…{….}…{….}….}

    There are several questions that need to be asked: Who is going to look at my code? Who is going to debug my code? Does my coding style help me?

    If you program for yourself – then it really doesn’t matter what you pick. But if your code is going to be read by someone else, then part of your responsibility is to help them out.

    Code elegance is small amount of easily readable code. Not code that takes up little space.

    -CF

  22. Parrot says:

    You’ve got to line up your curly brackets! No programming teacher I’ve ever had has ever advocated any other method. I didn’t even know any other methods existed until recently!

    What the heck kind of a complaint is "Oh, I just don’t feel comfortable giving a bracket it’s own line"?? It’s the start of an entire enclosed section of code, that’s not important enough for you?

    Having brackets that aren’t alligned with one another is like having matching bookends holding your books together but one of them is facing sideways and the other is facing forward. Sure it still works, but it just doesn’t look right!

  23. DavidE says:

    I’ve had to use all of these styles at one time or another, so I’m pretty flexible. K&R was really useful in the days when most of us programmed on 24×80 terminals. I did find one case where K&R style could prevent a problem. I had a programmer working for me who took the error messages produced by the compiler quite literally. There was a case where the compiler told him that there was a semicolon expected, so he added one:

    if (cond) ;

    {

    code that now always executes

    }

    With K&R style, the code would still work as written. Of course, the real problem was the programmer…

  24. A the B says:

    Being in an "Allman" shop has really made me hate the style. Taking up extra space for a { makes reading the code more difficult because it makes detecting the indentation of the code more difficult. It also makes catching and handling exceptions hard to read because a rather run-of-the mill exception handling routine can take up many screens. I used to use Allman style but converted to R&K when I realised that I found K&R easyer to read.

  25. Daniel DeLuca says:

    Allman is best. I have nothing more to add than what others have already posted. I have noticed more programmers have converted from K & R to Allman than vice versa. The arguments for Allman’s win hands down. End of discussion.

  26. Jeff Spindler says:

    I learned C from K&R and even while reading that book, I disliked that style, choosing instead to do what looks like is called Whitesmith’s.  Now I do Allmans, since that’s what VS does automatically – it’s hasn’t been much of a switch.

    One thing I do which VS’s auto formatter doesn’t like is to line up

      case ‘a’:

           // with the following

      break;

    so that it’s easier to spot missing break statements.

  27. Matthijs says:

    Call me stupid… but I am running Visual Studio 2005 express edition, but I can not change the default indentation style to Allman style! Who knows how to do it! Thanks.

    Of course, I found Tools/Options/Text Editor…

  28. danielfe says:

    Hi Matthijs,

    To change this, go to Tools…Options…Text Editor…C#…Formatting…New Lines… and make sure all the checkboxes under the "New Line Options for Braces" are checked. As you check and uncheck each one, you will see a "preview" screen that shows how the option will change formatting.

  29. Spedley says:

    Thanks danielfe that helped !

    If the New Line Options aren’t there you need to check the Show All Setting box in the bottom left.

  30. A_flj_ says:

    I came across text naming K & R Kernel style – maybe because it is used in the Linux kernel? Kernel seems easier to write to me, so I’ll use this name for it.

    I use Allman since ever. I didn’t imagine there could be another style until I encountered it in code written by others or downloaded from the net.

    This may be due to historical reasons. My beginnings as a programmer were in Pascal, almost 20 years ago. So switching from begin/end to {/} naturally led me to Allman.

    Nevertheless, I always considered Pascal a very readable language, perfect for ppl needing to write lots of code occasionally, but not being mainly busy writing code – back then I needed to code my own programs to drive machinery under DOS, my own programs to do statistical processing on data acquired, and the like, but there were long periods of time where I would only use the programs I wrote, and not enhance them.

    So it seems to me reasonable that Allman brings more readability into the code than Kernel.

    I encountered the argument that in C and C++, having the opening brace on the same line makes the difference between a function/method declaration and a function/method definition easier to spot. But I find this to be plain BS, since the difference is actually made by the presence or absence of the semicolon.

    I agree that at the time when you had to program in text mode in a 24 X 80 console screen real estate was expensive. But even back then you could change your video mode to 50 X 80, or something about that, and double your screen real estate. Besides, back then there were little compilers (any at all?) supporting exceptions, and it is my experience that braces tend to eat up disturbingly much space especially when you code exception handling using Allman.

    Today, however, screens have become big enough so you don’t really have a screen real estate problem anymore. You can even use two screens if your development/debugging process or your code is very complex. So why use a style which degrades readability?

    Another issue about readability: usually when i experiment with a solution, or in the initial versions of prototype code I write ugly, long blocks. During such tests, I also edit this ugly code a lot, add logging, remove logging, add conditional code in some place, move it into another place, etc. It often happens during such ugly and dirty changes (I wouldn’t call them quick, hoever), that I loose control over my braces. Using the proper indentation and the braces aligned like Allman, I don’t have such a difficult time spotting a missing brace, and I can use the environment to reformat the code after a change. Now, with Kernel I’d surely have a hard time following opening braces in all sorts of positions (at the end of a for/if/while, maybe after a multiline test condition for an if. Using Allman all opening braces are easy to spot in the starting position of individual rows.

    I’m about to start writing a coding standard for internal use. I guess anybody can tell which style I’ll recommend. The arguments presented by various ppl above surely helped me decide. until I reached this page, I was still thinking I must be missing somethign about Kernel if so mcuh code and so many coders use it. Now I think it’s just a historically determined bad thing, like many others.

  31. Jon says:

    K&R wins hands down for me.

    I used to be an Allman guy, since that seemed to be what most people were using. I then worked on a project which used K&R and was far more readable as a result.

    Like the person who commented before, I find it far easier to scan for if…} or while…} etc than {…}

    This is just plain horrible:

    try {

    }

    catch ( … )

    {

    }

    I also find it near impossible to get an overall picture of the structure of Allman code since so little of it fits on the screen.

  32. Pete says:

    K&R at all times.

    Also the style I remember from early C++ (C with Classes anyone?)  and Pascal.

    Perl let’s you put if/while statements at the end or beginning of a statement to emphasize what’s important.

    What’s more important – that there’s a block of code, or that there’s a block of code that might execute, or will loop more than once? Emphasizing the opening statement seems much more sensible to me.

    Allman’s style is good if you program for line counters, though. Especially when you do switch – case with braces.

  33. Mark Ross says:

    Anything except K&R.  I simply find it hard to read.  I have some odd SQL coding conventions that I follow, too, all in the name of readability.

  34. Sd says:

    IfYouWantToKnowWhatI1Is

    {

       read this;

       forget Allman

    }

    if_you_want_to_know_what_l1_is {

                   keep smiling;

                   use kernel style;

    }

    Never understood why searching for ‘{‘ is an issue (unless you are trying to remove it); just look at indentation. And 8 spaces of indentation is a blessing for anyone prone to writing unnecessarily complicated, hence less maintainable code.

    Just my thoughts…

  35. Jason Liang says:

    After I use Python, I enjoy programming in the K&R style.

  36. Adeon Writer says:

    I need Allman style. If I even use a piece of code that isn’t written in Allman style, I will make it Allman style. This is time consuming. I think of anyone who doesn’t use Allman style as making more work on me to properly indent their code. 😉 As far as how many spaces to indent, I’m not picky, so long as it’s consistent throughout it’s entire scope, and the matching brackets are equally indented.

  37. GC says:

    Allman style, 2-space tabs. I use 4-space tabs in python since blocks are indicated by tabs instead of braces.

  38. Tim says:

    Much prefer the K&R style. I used to be an Allman developer in college until I saw the light. More screen space to see your code is a plus but the main reason I like it is that the controlling statement nicely matches up with the ending brace. Visually it’s easier for me to see this than if I had an opening brace right below it.

    In the place I work now everyone uses Allman and it’s a nightmare looking at code that has a few lines in each if / else construct. The code just looks so bloated.

  39. Karl says:

    I have a lot of c / c++ books, and they mostly use Allman style…which I HATE!!

    I can understand the readabilty argument of Allman though, so I leave an additional space like Allman, but keep my opening brace on the first line.

    e.g.

    int function (params) {

       function code;

    }

    And if/else for loops are pretty similar.

    if (condition) {

    do this

    }

    EXCEPT, if there is only one line to be executed, in which case I write it like this.

    if (condition)

       do this;

  40. Dan says:

    I used to favor Allman style, but I switched to K&R when I had to deal with multiple programming languages (VB.NET, C#, Ruby). Although I can agree that Allman style is (at times) more readable, I favor the ability of K&R to allow just about ANY programming language to use the SAME number of lines.

    Examples:

    C/C++/C#/Java/PHP/Perl:

    ———-

    1    if (expression1) {

    2        statement1;

    3        statement2;

    4        statement3;

    5    } else if (expression2) {

    6        statement4;

    7        statement5;

    8    } else {

    9        statement6;

    10    }

    VBScript/VB6/VB.NET:

    ———-

    1    If Expression1 Then

    2        Statement1

    3        Statement2

    4        Statement3

    5    ElseIf Expression2 Then

    6        Statement4

    7        Statement5

    8    Else

    9        Statement6

    10    End If

    Pascal/Delphi:

    ———-

    1    if expression1 then begin

    2        statement1;

    3        statement2;

    4        statement3

    5    end else if expression2 then begin

    6        statement4

    7        statement5

    8    else

    9        statement6

    10    end;

    Ruby:

    ———-

    1    if expression1

    2        statement1

    3        statement2

    4        statement3

    5    elsif expression2

    6        statement4

    7        statement5

    8    else

    9        statement6

    10    end

    COBOL:

    ———-

    1    IF EXPRESSION-1

    2        STATEMENT-1

    3        STATEMENT-2

    4        STATEMENT-3

    5    ELSE IF EXPRESSION-2

    6        STATEMENT-4

    7        STATEMENT-5

    8    ELSE

    9        STATEMENT-6

    10    .

    Python's indentation rule is an annoyance, because I strongly feel that progressive INdentation must be followed by eventual progressive DEdentation. If something is indented 4 spaces, there must be something present on a line that dedents this block 4 spaces. I might think of using a comment to denote the end of the block

    Python:

    ———-

    1    if expression1:

    2        statement1

    3        statement2

    4        statement3

    5    elif expression2:

    6        statement4

    7        statement5

    8    else:

    9        statement6

    10    #end if

  41. Andrew Dunn says:

    Whitesmiths Style all the way, it makes my code look cleaner, as well as making the distinction that braces are part of the block of code, NOT the opening statement.