Go Down

Topic: Indenting & Formatting Styles - which do you use? (Read 4395 times) previous topic - next topic

FalconFour

Sometimes when I read someone else's code, I cringe... the spacing and indenting seems so foreign, it takes twice as long to read a block of that code than some of my own code. Both programs compile, of course, but a C program could be smashed together on one single line and it would still compile ;)

Got me wondering... what style do most people use here? To describe these admittedly rather unfamiliar types, I turn to Wikipedia...

  • K&R Style
    [K&R style] keeps the first opening brace on the same line as the control statement, indents the statements within the braces, and puts the closing brace on the same indentation level as the control statement (on a line of its own). Functions, however, are braced distinctly from statements; an opening function brace is placed on the line following the declaration, at the same indentation level as the declaration.
    Quote
    int main(int argc, char *argv[])
    {
        ...
        while (x == y) {
            something();
            somethingelse();

            if (some_error)
                do_correct();
            else
                continue_as_usual();
        }

        finalthing();
        ...
    }

  • Variant: 1TBS
    In this style, the constructs that allow insertions of new code lines are on separate lines, and constructs that prohibit insertions are on a single line. This principle is amplified by bracing every if, else, while, etc.--even single-line conditionals--so that insertion of a new line of code anywhere is always "safe".
    Quote
        if (x < 0) {
            printf("Negative");
            negative(x);
        } else {
            printf("Non-negative");
            nonnegative(x);
        }

  • Allman Style
    This style puts the brace associated with a control statement on the next line, indented to the same level as the control statement. Statements within the braces are indented to the next level.
    Quote
    while (x == y)
    {
        something();
        somethingelse();
    }

    finalthing();

  • GNU Style
    Like the Allman and Whitesmiths styles, GNU style puts braces on a line by themselves, indented by 2 spaces, except when opening a function definition, where they are not indented.[7] In either case, the contained code is indented by 2 spaces from the braces.
    Quote
    static char *
    concat (char *s1, char *s2)
    {
      while (x == y)
        {
          something ();
          somethingelse ();
        }
      finalthing ();
    }

  • Lisp Style
    A programmer may even go as far as to insert closing brackets in the last line of a block. This style makes indentation the only way of distinguishing blocks of code, but has the advantage of containing no uninformative lines.
    Quote
    for (i = 0; i < 10; i++) {
         if (i % 2 == 0) {
             doSomething (i); }
         else {
             doSomethingElse (i); } }


I think everyone has their own style, but probably falls primarily under one of these definitions. Personally, my style is most like K&R, where I try to collapse the (visually pointless) curly braces onto their relevant line as much as possible - that is, since a curly brace defines a data array, or a function, it should be on the same line as what defined it (like "void myFunction (byte parm1) {"). Most styles seem to put the brace on its own line all by itself, which I see a lot as well. For readability, sometimes I expand a long control statement into multiple lines, or expand one-liner "if/else" statements to their own lines.

Thoughts? :D

AWOL

You missed few:
http://en.wikipedia.org/wiki/Indent_style

FalconFour

Didn't miss... that's the article I linked to. I just didn't think I should blow up the first page of the topic with 11 different options, so I picked out the ones that looked the most common and added an "other". Did I miss one you would've picked...?

AWOL

I use this:
Code: [Select]
if (x) { but loathe, with a passion that verges on murderous this:
Code: [Select]
void loop () {

RoyK

Allman style hands down.

Code: [Select]

if(something)
{
    DoSomething(a);
    DoSomethingelse(b,c);
}


Makes it SO easy to see where a compound statement begins and ends - especially with a good editor like UltraEdit which automatically draws a fine vertical line between matching braces.


robtillaart

Prefer Allman style, but any style is good IFF used consequently => problems occur when style is not used consequently. (Python enforces one style, isa good thing)
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

retrolefty


Allman style hands down.

Code: [Select]

if(something)
{
    DoSomething(a);
    DoSomethingelse(b,c);
}


Makes it SO easy to see where a compound statement begins and ends - especially with a good editor like UltraEdit which automatically draws a fine vertical line between matching braces.




I don't care what style's name is called or if I even follow all the rules within a given style, but I 100% agree that braces should be on lines by themselves. The arduino IDE editor has a nice brace matching feature and along with braces on seperate lines really helps me as I'm writing or modifiying my sketches.

Lefty

liuzengqiang

I didn't know I was doing the popular "Allman" indentation. I just thought other ways were lame  ]:D

Especially when you have many layers of indentation, indenting the curly brace after control statements will make an old 80-line monitor scream. Well, not if you have fancy GUI IDEs that can fold the layers nicely for you.
Serial LCD keypad panel,phi_prompt user interface library,SDI-12 USB Adapter

FalconFour

Surprised to see so many people supporting curlies-on-their-own-line... that drives me absolutely crazy!! It makes it harder to visually pick out the top of a block from the indentation - the brace by itself at the previous indentation level blends in with the code block starting at the next level, and stands out as a gratuitous waste of a line break... all those excess line breaks sparse the code out and make for extra scrolling to find a part of the code. Sometimes, the syntax gets so bad that I have to throw the code into Eclipse's formatter (which is still the only thing I've found useful in Eclipse) and have it give me readable code! =P
(* edit: haha, good timing @liudr *nudge nudge* ;) )

I would say "to each their own" but I just don't get it... I'm trying to figure this one out. What's so crazy about putting braces on the lines they belong to?  :~

FWIW, I rarely if ever ("never", really) use the braces-collapsing functions... maybe I should get into the habit =P

AWOL

Quote
What's so crazy about putting braces on the lines they belong to?

Nothing whatsoever -that's the Linux way!

FalconFour


Quote
What's so crazy about putting braces on the lines they belong to?

Nothing whatsoever -that's the Linux way!
Well, you were the guy that said you may be prone to murder someone upon encountering my code... =P

Code: [Select]
void DisplayReadMenu() {
  while(1) {
    lcd.clear();
    if (select_list(&readMenu) == -3) return; // left arrow -> back to main
    while (wait_on_escape(25)) ; // let go please
    switch (readMenu.low.i) {
      case 0: DisplayIDData(); break;
      case 1: DisplayChargeData(); break;
      case 2: DisplayStatistics(); break;
      case 3: return; break;
      default: break;
    }
    lcd_reinit_phi();
    delay(500);
  }
}

(and I don't usually do the inline "case" thing, but in that type of scenario it REALLY helps improve readability, IMO.)

AWOL

Quote
Well, you were the guy that said you may be prone to murder someone upon encountering my code... =

I've done a lot of Linux systems programming, and never seen functions declarations like that.

FalconFour

#12
Jun 23, 2011, 09:43 pm Last Edit: Jun 23, 2011, 09:46 pm by FalconFour Reason: 1

Quote
Well, you were the guy that said you may be prone to murder someone upon encountering my code... =

I've done a lot of Linux systems programming, and never seen functions declarations like that.

Could be related to (and not meaning to brag) "informal" education of all programming-related topics... learned PHP by tweaking forum code, then building a fully automated, self-maintaining file-hosting website, then got into Arduino and learned most of that by trying to extend the MPGuino project. Never did go to school for this stuff, never read a book on it, just learned by example and documentation :)

So the way it makes sense to me, is that only lines that "tell you something" should take up line space... the function declaration tells you "this is what this block does", and of course the brace goes on that same line because that's where it begins. The closing brace goes on its own line because it says "that's the end of this block". Everything else, like one-line "if" statements, follow logical flow... "if this, do that", and "if this, do.... all this .... end" for an "if (blah) { do(blah); }" block. It just always made sense to me like that...

edit: Oh, the "while (1)" thing makes me shiver too... I hate doing infinite "while" loops. That was part of the phi_prompt example code I originally based the menu functions on, never bothered to find a more elegant way to catch and loop ;)

liuzengqiang

Copy-paste friendly :)

If I had many "}" on the right side of a line I need to copy I have to delete them after copying the whole line.
Serial LCD keypad panel,phi_prompt user interface library,SDI-12 USB Adapter

maniacbug

Of course, if other's code bugs you, you can always run it through Artistic Style.

Oh and hey guess what, Allman formatting is the first preset, "-A1".  And my vote.  As soon as I can figure out how, I'm going to write a git filter to automatically run "astyle -A1 -s2" on code before commits.

Go Up