“Kernighan Ritchie versus Allman” or “Where do you put the seagulls?”

ascii sunset

Where do you put the seagulls, the curly braces, the flower brackets, the squiggly brackets, the gullwings? In Swedish they are usually called “måsvingar” or “krullparenteser”.

I’m talking about to the brackets commonly used in many programming languages to enclose blocks of code.
One classic dispute among hackers is whether you should put the opening brace is on the same line as the “header statement” or on the next.

The two coding styles can be referred to as the Kernighan Ritchie style and the Allman style.

The best analysis and assessment that I’ve found of these styles is made by David Straker in his book “C Style: Standards and Guidelines“ from 1991. The following code examples are taken from his book.

The Kernighan Ritchie style means that the opening brace appears on the same line:

if ( PageWidth > PaperWidth ) {
    SetPageWidth( PaperWidth );
    TellUser( MSG_PAGE_CHANGED );
}

In the Allman style the opening brace appears on the next:

if ( PageWidth > PaperWidth )
{
    SetPageWidth( PaperWidth );
    TellUser( MSG_PAGE_CHANGED );
}

Many programmers say that the Allman style is wasteful of space, making the code longer which in the end means that you have to scroll up and down more than what is necessary.

But consider what happens when the header statement is more complex so that it encompasses more than one line:

Kernighan Ritchie style:

if ( PageWidth > PaperWidth || PageWidth < PG_MIN_WIDTH ||
    IsNewDocument() ) {
    SetPageWidth( PaperWidth );
    TellUser( MSG_PAGE_CHANGED );
}

In this example it’s not completely clear where the header statement ends and the block begins. The Allman style, seems like a much better option.

if ( PageWidth > PaperWidth || PageWidth < PG_MIN_WIDTH ||
    IsNewDocument() ) 
{
    SetPageWidth( PaperWidth );
    TellUser( MSG_PAGE_CHANGED );
}

Kernighan Ritchie style refers to the coding style described by Brian Kernighan and Dennis Ritchie in their classic The C Programming Language from 1978.

Allman style refers to programmer Eric Allman. It can also be called the BSD style.

sunset.on.dark.3special

Annonser

Kommentera

Fyll i dina uppgifter nedan eller klicka på en ikon för att logga in:

WordPress.com Logo

Du kommenterar med ditt WordPress.com-konto. Logga ut / Ändra )

Twitter-bild

Du kommenterar med ditt Twitter-konto. Logga ut / Ändra )

Facebook-foto

Du kommenterar med ditt Facebook-konto. Logga ut / Ändra )

Google+ photo

Du kommenterar med ditt Google+-konto. Logga ut / Ändra )

Ansluter till %s