Indenting & Formatting Styles - which do you use?

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 :wink:

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.
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".
    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.
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.
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.
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? :smiley:

You missed few:

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

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

Allman style hands down.

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.

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)

RoyK:
Allman style hands down.

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

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

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.

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 :wink: )

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

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

Nothing whatsoever -that's the Linux way!

AWOL:

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

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

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.

AWOL:

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 :slight_smile:

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 :wink:

Copy-paste friendly :slight_smile:

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.

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.

Looks like I'm closes to 1TBS, although I'd never heard it called that, and the examples don't have enough different constructs to capture the nuances.

void func (int a)
{
    if (a == 0) {
        while (1) {
            foo();
        }
    } else if (getch(long, list, of,
                     arguments, for, func)) {
        switch (a) {
        case 1:
            bar();
            break;
        case 2:
            baz();
            break;
        default:
            break;
        }
    }
}

Normally four space indents and tabs that are assumed set every 8 spaces, but I'm not militant about those.

I like, in the Python style guide where it says essentially, "above all, maintain readability".

int main() {

  if(condition) {
    ...
  } else {
    ...
  }
}

I also use a lot of whitespace within code blocks, sometimes even on the first line, in order to improve readability. But I never put opening braces on their own line.

I never put opening braces on their own line.

I suspect that the reason for that is that the code base I'd worked on for the last 20+ years originated back before "new style" function definitions, so you would have:

void foo (a, b, c)
  int a, b;
  char c;
{
   // Function
}

Having the open brace on the same line as the last argument definition would have been awful.

I vote for what I guess is the K&R style. I probably like it because I started with the K&R book many years ago. Also I used to work for a company that enforced strict K&R "syntax" (if that's the right word) with no fancy new libraries or features.


Rob