Found at: http://publish.ez.no/article/articleprint/27/

Coding Standards - Part 2 - Basic conventions



Coding standards define a standard for the look and feel of your code. This is helpful to most projects, and to some it is a necessity. Especially in open source projects. In this second issue I'll show eZ system's standards regarding macros, indentation and brackets.

Macros


Macros and other # commands are to be avoided. Exceptions are #include and the necessary #ifndef/#define/#endif in header files. Macros can be used when there are good reasons to do so, though.

Indentation


Use 4 character indentation, this is commonly used and allows for easy recognition of the indentation level. Use spaces in stead of TABs, to assure the code looks the same everywhere.

Bracket placement


Put begin and end brackets {} on the same column, and on the same column as the statement that "owns" the brackets.

Example

int meaning( int x, int y )
{
    if ( x == y )
    {
        ..
    }
    else if ( x > y )
    {
        ..
    }
    else
    {
        ..
    }
    return 42;
}



Parentheses, brackets and comma


Use a space after every comma. Use a space after a begin parenthesis, and a space before an end parenthesis. Do not use such spaces for square brackets. Use one, and only one space between each type. Put pointer * and reference & signs adjacent to the variable they belong to.

Use empty lines to group variables and codelines that logically belongs together. Variable names that are grouped this way must be on the same column. Empty lines must be empty, containing no TABs or spaces.

If you are unsure of the execution order of an expression, use more than the minimum required number of parentheses and remove them when it becomes more clear.

If statements and while loops


Nested if statements must use brackets {}. If you have many consecutive if and else if statements, consider using case statements instead, or redesign using a more object oriented approach.

If statements and while loops can only execute boolean expressions, never assign or change any data.

The next issue of this article will be a bit longer and more advanced, as I'll advance to topics such as naming conventions, functions, classes and namespaces.


| Back to normal page view |