Coding style

From WarzoneWiki

Jump to: navigation, search

We are trying to follow the coding style that is predominant in the old Warzone code. Please use this style in your patches.

This means your code should look like this (note spaces, braces and line endings):

 void functionName(const char *variableName, int *anotherVar, STRUCTURE *psStruct)
 {
     if (variableName == NULL)
     {
         *anotherVar = 1 + 2 * (5 / 2);
     }
     else
     {
         *anotherVar = 1 + 2 * (atoi(variableName) / 2);
     }
 }

Indentation for scope should use tabs, while indentation for lining up wrapped lines should use tabs to align with the start of previous line, then spaces. This way the code will look readable with any tab size. For example, when a line with a two-line printf begins, use tab to indent it, then use tab then spaces to indent the following line, like this (\t for tabs):

 \t\tprintf("some text on this line that got long, "
 \t\t       "some more text on the next line");

We follow the C89 standard since we want the code to be compilable with C++ compilers. We use variadic macros and C99 comments though (which are ISO C++ as well as C99):

 #define VARIADIC_PRINT(...) do { printf(__VA_ARGS__); } while(0)
 // I'm a C99 comment! I'm lucky to be in Warzone 2100!
 /* I'm an old fashioned C89 comment, still pretty useful.. */

More things to do:

  • Avoid reserved C++ keywords (try, catch, throw, template, class, etc.).
  • Put variables at the beginning of declarations.
  • Comment always why you do something if this is not obvious.
  • Comment how you do it if it may be difficult to follow.
  • Do not comment out code you want to remove (just remove it, Subversion can always get it back).
  • Always add braces following conditionals (if).
  • Put curly braces on lines of their own
  • Use C99 fixed size types only where necessary. Otherwise use usual C types.

Make sure your patch does not add any new compiler warnings.

GNU Indent

For gnu indent, you can use the following switches:

 indent --dont-break-procedure-type --no-space-after-function-call-names --use-tabs --tab-size4 -i4 --brace-indent0 --line-length120 <files>

Artistic Style

For astyle, save the following as "astyle":

 suffix=none
 indent=tab
 brackets=break
 indent-switches
 pad=oper
 unpad=paren
 min-conditional-indent=0
 mode=c
 indent-preprocessor
 one-line=keep-statements
 max-instatement-indent=8

and call astyle like:

 astyle --options=astyle <files>