Thread: A Question of Style

  1. #1
    Registered User DreamThink's Avatar
    Join Date
    Feb 2013
    Posts
    8

    A Question of Style

    Hi folks,

    As I code practice projects from my C book, there are many times where the author recommends using or not using braces, and earlier in the book gave a few examples of how different programmers might indent the case statements in a switch.

    It's been indicated that whitespace, as well as comments, are ignored by the compiler. So, this leaves quite a bit of leeway for ways of arranging the code.

    My question is how do you guys & gals who have been programming forever handle braces? I've tried the following:

    Code:
    frootloops {
        milk {
            cookies;
        }
    }
    
    juicyfroot
    {
        shinyfoil
        {
            gum;
        }
    }
    
    hoolaloops
    {    dizzy
        {    spinning;
        }
    }
    
    fuzzy
        {
            wuzzy
                {
                    wuzzabear;
                }
        }
    The examples in the book follow the frootloops style. The IDE I'm using, CC386 IDE (switched to it from Pelles because Pelles gave me errors typing in C89 style) defaults to the juicyfroot style. The fuzzy style I have seen in some of the other books I've looked at.

    However, I seem to like the hoolaloops style, which I found accidentally by backspacing. I can follow the vertical trail of braces and keep track of which nest I'm in, and having the line of the next nest on the same line as the first braces seems to save a little space.

    I know it's probably just a question of personal taste, but I do think it's important. Several books have mentioned how important it is to clearly name identifiers, and pick a readable, consistent style for nesting and braces.

    So, any thoughts are appreciated!

    Thanks,
    DT

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I prefer and use the first style, but frequently deal with code done like the second style - and that's OK, as well.

    I like to be flexible, but any other style besides #1 or #2, doesn't work for me.
    Code:
    #1:
    frootloops {
        milk {
            cookies;
        }
    }
    
    #2:
    juicyfroot
    {
        shinyfoil
        {
            gum;
        }
    }

    This one is especially hideous:
    Code:
    Unimaginably
          {
               poor;
                  {
                       creator was
                             {
                                   apparently on drugs
                             }
                  }
          }

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Some style issues can help debugging or prevent errors when code maintenance comes up, for example

    Code:
    if (foo)
       do_something();
    else
       do_something_else();
    If you later decide to add a statement to the first part of the branch and forget to add braces, the compiler will probably complain, but if you do the same with the else branch (and forget the braces) then you will produce a difficult-to-find bug. For this reason some people recommend simply always using the braces. It's an easy rule to follow. However, if you find such a rule useful it doesn't mean you should start going through your old code and "correct" violations of this rule.

    Also the style doesn't matter so much as it is easy to use. Your suggestion of hoolaloops looks like it is difficult to maintain. Imagine you restructure your code logic or add/delete statements. With the standard brace styles this is straightforward and many code editors even will recongize the style and refactor the edits for you, but if you need to do a lot of extra work this is bad. For this reason I consider the following bad:

    Code:
    char *gender;       // male or female
    char *preTitle;     // Mr., Mrs., etc
    char *fullName;     // John Smith, etc.
    The writer seems to want all of the comments to line up together. This reads fine but is annoying to edit. Just place comments directly after the code if there is room, otherwise place them on their own line.

  4. #4
    Registered User
    Join Date
    Mar 2011
    Posts
    596
    Of the four examples, I would use this:
    Code:
    hoolaloops
    {    dizzy
        {    spinning;
        }
    }
    for two reasons:

    1) Braces pair up vertically and so are easy to check that both are present, and which goes with which.

    2) Minimun number of lines used.

    However, I don't use them unless needed. I find that indentation and blank lines are
    all I need to make the intention of the code clear and easily readable.
    For multiple statements in blocks, I would use braces as in hoolaloops above, and
    for the same two reasons.

  5. #5
    Registered User
    Join Date
    Feb 2013
    Posts
    8
    Though my statement will be controversial, there is only one correct answer to this. Juicyfroot. The reason for this is in the following example of Microsoft C#. That's what Microsoft uses in their examples. That sets the standard. Follow the leader. I'm not kidding. Ignore anyone who says anything else.... Indent by 4, though. 2 is too small, 3 looks okay but is an odd number, so 4 is what we're stuck with and 4 happens to be half of an 8-character tab. C# is the natural successor to C and C++, so start abiding! When the biggest congregration of professional software engineering genius in the world decides to do it this way, it doesn't make sense to do any different.

    http://msdn.microsoft.com/en-us/libr...=vs.71%29.aspx

    Code:
    // Hello1.cs
    public class Hello1
    {
       public static void Main()
       {
          System.Console.WriteLine("Hello, World!");
       }
    }
    Last edited by thickster; 02-17-2013 at 10:55 PM.

  6. #6
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    4 character indent
    Starting brace doesn't get its own line
    Whitespace between tokens and binary operators in general

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by thickster View Post
    Though my statement will be controversial, there is only one correct answer to this. Juicyfroot.
    Your statement is not controversial. It is simply wrong.

    There is no correct answer. There are only preferences of people. It is up to particular people, or particular teams of people, to decide what coding style or styles they accept. And, more importantly, to justify that choice where appropriate and manage any consequences (most notably, productivity of programmers and any flaws in code) of that choice.

    Quote Originally Posted by thickster View Post
    The reason for this is in the following example of Microsoft C#. That's what Microsoft uses in their examples. That sets the standard. Follow the leader. I'm not kidding.
    Yes, you are kidding, but I'll go along in order to make a point. Microsoft has internal coding style guidelines, but doesn't presume to claim that their coding style guideline is right for anyone outside Microsoft and everything else is wrong.

    Quote Originally Posted by thickster View Post
    C# is the natural successor to C and C++, so start abiding!
    C# is one of the bastard children of C++. Given some social irregularities in C's parentage of C++, the bastard children of C++ have trouble gaining support for any claim that they are a successor of C.

    Most bastard children rely on the benevolence of their parents or have to survive on their merits. Some bastard children manage to convince a few foolish people to lobby on their behalf in asserting their claim of succession, and trying to push others to do things that suit the bastard children. Meanwhile, those who have productive working relationships with the parents or grandparents just get on with doing the work they are supposed to do.



    To come back to the original question, I generally prefer the style described in this thread as "juicyfruit". When using control structures (if, while, for, etc) I always place statements within a block with the same style if indenting braces. I use a tabbing increment (the number of spaces of additional indentation of a new brace) of three characters.

    The reasons are;
    1) No need to rely on code highlighting to align a opening brace with a closing brace on screen. I simply look at the column number in my editor.
    2) If I want to add code into a block, I know where the braces are.
    3) I also deliberately structure code into small functions, so rarely run into a situation - even with the additional vertical space implications of the "juicyfruit" compared with other styles - where a function cannot be displayed on a small screen, or on a single printed page.
    4) I am able to contain length of a line of code, so it is able to be displayed in a narrow screen (less than 80 characters wide) or page.
    5) Unlike what occurs with the hoolahoops style, if I need to add a code statement at the start of a block, it is not necessary to break an existing line.



    I don't claim this style is right for everyone. However, I have found - based on experience - that this style is more productive and less error prone for my method of programming.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  8. #8
    Registered User
    Join Date
    Mar 2011
    Posts
    596
    Quote Originally Posted by grumpy View Post
    ...

    I don't claim this style is right for everyone. However, I have found - based on experience - that this style is more productive and less error prone for my method of programming.
    That should have been part of everyone's reply.

    My style has evolved a little bit over time, but has remained the same within any particular program.
    I find it important to follow your own style rules, just as it's important to follow language rules
    (though not as catastophic if you don't, obviously).

    As I am not a professional programmer, I have an advantage of not having to produce large
    amounts of code. My programs are often quite large though. Still I find that most of my time is spent
    thinking about what I want or need to do, and less of my time actually typing it in. So I have the
    luxury of time to neaten up the appearance of the code. I find it to be little work to insert a new
    statement on the same line as the opening brace. If I know I'm probably going to be inserting one,
    then I'll leave the opening brace on it's own line till I'm finished. But again, I have the luxury of
    neatening it all up onto one line.

    It would be more interesting to see a whole page of code in various styles, instead of one statement.

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I tend to use juicyfroot (aka Allman), which I find to be the most clearest and cleanest way to write code.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Personally, I prefer the OTBS
    Code:
      // case 1
      // with braces, and good indentation
      for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
          if (arr[i][j] == -1) {
            arr[i][j] = 1;
            count++;
          }
        }
      }
      printf("Success\n");
    
      // case 2
      // with braces, but a train-wreck indent
      // The compiler doesn't care, but human readers
      // are puking over the keyboard
            for (int i = 0; i < m; i++) 
       { for (int j = 0; j < n; j++) { if (arr[i][j] == -1) {
            arr[i][j] = 1; count++;
          } } }
      printf("Success\n");
    
      // case 3
      // without braces, but correctly indented
      // it's not what the compiler sees, but as a programmer
      // you know what it all means
      for (int i = 0; i < m; i++) 
        for (int j = 0; j < n; j++) 
          if (arr[i][j] == -1) 
            arr[i][j] = 1;
            count++;
      printf("Success\n");
    Presumably, brace counters have no problem parsing case 2 any slower than parsing case 1.

    My point about case 3 is that if you use indentation to convey the program flow, and only (in a loose sense of getting a formatter to turn case 2 into case 1) rely on braces to tell you the meaning when the indentation is all screwed up. Braces are syntactic sugar for the compiler. For that reason, I prefer the compact forms.

    Any programmer could add the braces to case 3 and preserve the meaning without any difficulty at all.

    Maybe part of the reason is I'm from the old school, who learnt to program on 80x25 teletypes, where burning half the screen height on empty lines containing only braces was not a good use of the resources.

    The only real rule when it comes to your choice of brace style is to be consistent about it.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Salem View Post
    The only real rule when it comes to your choice of brace style is to be consistent about it.
    The second unspoken rule is to use a "sane" style. Otherwise one might as well choose case 2 which everyone will puke over.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User DreamThink's Avatar
    Join Date
    Feb 2013
    Posts
    8
    Great spread of opinions and perspectives here, thanks a bunch guys. And thanks MOD for moving my thread to the appropriate sub board.

    @Salem, it's interesting in the code blocks you posted you use 2 spaces for indentation. While others are advocating 3, and 4 spaces for indentation. I had no idea there was a wiki devoted to indent styles, but it doesn't surprise me, and it was an enjoyable read.

    Looking over the different styles, it seems like the Allman style would be easier for, say, a beginning programmer to use and maintain, as both braces stand out and the vertical trail of code is easy to follow. However, having said that, the K&R flavor might be useful to help me get into the mindset of focusing on the control statements themselves as the guide to program flow, instead of the braces. I think I'll try both when coding future projects from the manual, and see which one feels more intuitive.

    I hadn't considered the number of spaces for indentation, the IDE is set to a default of 4. But looking at the 2 space option, the code is certainly more compact horizontally, and at first glance--because it's not so spread out, might be more expedient when picking through nested code. I may play around with that too, although ultimately I'd like to get used to a convention that most professionals are using. Perhaps we'll get a few more replies to get a broader sample of opinions on the subject(s).

    Thanks again,

    DT

  13. #13
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by Elysia View Post
    Otherwise one might as well choose case 2 which everyone will puke over.
    Look at code in the first questions asked by a lot of forum members (of which a fair percentage drop out, never to be seen again, when they find this site is not a free homework factory) and you will see a considerable number of variations of "case 2".
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by DreamThink View Post
    ...although ultimately I'd like to get used to a convention that most professionals are using...
    You do not seem to have learned the lesson people are trying to convey here.
    There is no ultimate style. There is no single style that professionals are using. There is no "professional" style.
    Everyone has their own style. Companies have their own style. Projects have their own style.
    So, once more: pick a style you think is best for you and stick with it. Feel free to experiment.

    Quote Originally Posted by grumpy View Post
    Look at code in the first questions asked by a lot of forum members (of which a fair percentage drop out, never to be seen again, when they find this site is not a free homework factory) and you will see a considerable number of variations of "case 2".
    Which is a bad thing, so I don't see your point...?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    A fair amount of newbie code is typified by an indentation style called none at all. Everything is just a bunched up mess down the left hand column. On the plus side, "indent0" is a pretty reliable indicator that the code has simply been copy/pasted from somewhere else, and in the process, the indentation is lost.

    @Salem, it's interesting in the code blocks you posted you use 2 spaces for indentation. While others are advocating 3, and 4 spaces for indentation. I had no idea there was a wiki devoted to indent styles, but it doesn't surprise me, and it was an enjoyable read.
    With infinitely variable font scaling, it's hard to choose
    If I pick a large font size, then 2 spaces seems perfectly adequate. But if the font gets smaller then 4 spaces is much more preferable.
    I also tend to use 2 spaces when indenting the code by hand rather than letting the editor autoindent for me (such as when typing code on a forum).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Concatenating C style Strings Question
    By bengreenwood in forum C++ Programming
    Replies: 3
    Last Post: 03-19-2009, 03:19 PM
  2. Defining a Union - A Question of Style
    By clark.leach in forum C Programming
    Replies: 6
    Last Post: 11-21-2008, 08:13 PM
  3. C style arrays question
    By Raigne in forum C++ Programming
    Replies: 3
    Last Post: 04-12-2008, 12:06 AM
  4. if...else...finally? question about style
    By Nyda in forum C Programming
    Replies: 17
    Last Post: 11-24-2004, 10:20 AM
  5. C++ Style Question
    By Davros in forum C++ Programming
    Replies: 7
    Last Post: 11-17-2004, 03:52 AM