Programming

C/C++ Brace Indent Style

One of the commonest questions asked by the beginner C/C++ programmer is about the proper way to indent C code, especially with respect to curly braces.  Well, if you've ever wondered about this, you've come to the right place!.

Why Indent Curly Braces?

Simple - it makes code more readable.  Human readable that is.  The compiler doesn't care what style (or lack of) you use with regards to indenting code.  Indenting doesn't form part of the syntax of either C or C++ (or any other programming language)

The Styles

A statement can be either a simple statement or a compound statement. A compound statement is defined as a block of statements that are grouped together using braces. What this means is that the braces form part of the compound statement itself and not part of the controlling statement.  Braces are always in pairs consisting of:

  • one opening brace - {
  • one closing brace - }

The pair of braces should be at the same level of indentation.  The indentation of the braces should also match that of the statements in the block.

Here are the four styles that most common:

Whitesmiths Style
   if (condition)
      {
      statement1;
      statement2;
      }
GNU Style
   if (condition)
     {
       statement1;                     
       statement2;
     }

Note that the indents are always four spaces per level, with the braces halfway between the outer and inner indent levels.

BSD/Allman Style
   if (condition)
   {
       statement1;
       statement2;
   }
K&R/Kernel Style
   if (condition) {
       statement1;                     
       statement2;
   }

This is probably the most confusing style (it's hard to keep track of the braces properly), although it is used in many books (perhaps to reduce on the lines that the code takes up!).

Best Style to Use

Looking around at code, you'll find that the Whitesmiths and BSD/Allman styles are the most common - choose to follow one of these and your code will be both easier to follow by you and others!



Adrian Kingsley-Hughes
Last updated: May 4th 2004
Print This Page   |   Email me when this page changes    |  Search This Site



Crucial.com System Scanner does the work for you!



links.inc"); ?>

Contact Us