Last update May 24, 2007

Curly Brace Placement



Discussion of the placement of {} braces traditionally descends into a heated argument, or even a quasi-religious war. Many programmers prefer to format their code in a way that emphasises the code structure, clearly seperating blocks of code; others prefer a format which wastes as little vertical space as possible. Because this preference depends on your personality, it's rarely productive to discuss which style is "best".

However, it is possible to agree on names and minimal descriptions of the styles. If you're fanatical about a particular style, it will help everyone if you can describe it succintly.

Additionally, all style guides seems to be in widespread agreement on a few points:

  • Only one opening brace per line.
  • more...

BSD or Allman style

(I don't know where that name comes from, I think Allman was one of the original BSD programmers).

class A
{
  int func (int x)
  {
    if (x==2)
    {
       return x*3;
    }
    else
    {
       return x*4;
    }
  }
}

Condensed BSD style

class A
{
    int func (int x)
    {   if (x==2)
           return x*3;
        else
        {   // Multi line
            x+=4;
            return x;
        }
    }
}

Stroustrup

 ( http://public.research.att.com/~bs/bs_faq2.html)
Functions are on a line by themselves

class A {
  int func (int x)
  {
    if (x==2) {
       return x*3;
    }
    else {
       return x*4;
    }
  }
}

Java

( http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html)

class A {
  int func (int x) {
    if (x==2) {
       return x*3;
    } else {
       return x*4;
    }
  }
}

Eckel

( http://www.camtp.uni-mb.si/books/Thinking-in-C++/TIC2Vone-distribution/html/AppendixA.html)

class A {
  int func (int x) {
    if (x==2) {
       return x*3;
    }
    else {
       return x*4;
    }
  }
}

Alignment on Brackets (AoB)

class Class
{
        void foo (bool blah)
        {
               if (blah)
                  {
                  // do something regarding blah
                  writefln ("blah is true");
                  blah = false;
                  }
               else
                  {
                  // do something else
                  writefln ("blah is false");
                  }

               foreach (char line[]; lines)
                       {
                       line ~= "\n";
                       writef (line);
                       }
        }
}

FrontPage | News | TestPage | MessageBoard | Search | Contributors | Folders | Index | Help | Preferences | Edit

Edit text of this page (date of last change: May 24, 2007 19:19 (diff))