Gromacs

Code Formatting

    Redirected from Developer Zone/Programming Guide/Block Structure
    Table of contents
    1. 1. Indentation
    2. 2. Block Structure

    Indentation

    In order to properly comprehend code indentation is crucial. We recommend the following layout for all new code:

    • 4 spaces indentation for each level. If you are running out of screen space you should use this fancy new feature called "function"  ;-)
    • Do not use tabs, spaces only - most editors can be set to generate spaces when you press the tab key! Tabs are inconvenient, e.g, when doing git diff, because the indendation may appear very different from what it is in your editor.
    • Avoid trailing whitespace. It's invisible in most editors by default, but can cause confusion when you unintentionally remove or add it, because that still counts as a change for git on that line. git diff with colors shows all trailing whitespace very clearly.

    This can be enforced by writing this comment as the first line in your source file (when using emacs).

    /* -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*- */ 

    Then, after you inserted this, you return to the top of the file, press Ctrl-space, go to the bottom of the file and type Esc-x indent-region. Your source code file is now indented correctly according to GROMACS standards. It may be necessary to close and re-open the file, since emacs reads this magic comment only upon file opening.

    Block Structure

    In order to make the source code readable always use braces around blocks, and put braces on the next line, even if it is unambiguous. Use

    if (foo) 
    {
        blah();
    }
    else 
    {
        bleh();
    }
    
    for (i=0; (i<imax); i++)
    {
        printf("Foo %d\n",i);
    }

    rather than:

    if (foo)
      blah();
    else
      bleh();
    for(i=0;i<imax;i++) 
      printf("Foo %d\n",i)

    Note that there is an empty line between the two logical blocks (if statement and for loop)

    Try to add a comment before a loop or conditional statement to tell *why* you are doing something, not what you are doing. Most users hacking the code know that i++ means that you incrementing i, but why are you incrementing it?

    Spaces are good - that's what the space-bar on your keyboard is so large :-) Personally I feel that e.g. using parentheses around the i<imax test in the loop above is unnecessary, but to make a point I won't alter it: if in doubt, use spaces or parentheses! --Lindahl 21:14, 27 February 2009 (CET)

    Powered by MindTouch Core