Why Have A Coding Style?#
For easier maintenance#
If you’re merging changes from a patch it’s much easier if everyone is using the same coding style. This isn’t the reality for a lot of our code, but we’re trying to get to the point where most of it uses the same style.
Improved readability#
Remember, code isn’t just for compilers, it’s for people, too. If it wasn’t for people, we would all be programming in assembly. Coding style and consistency mean that if you go from one part of the code to another you don’t spend time having to re-adjust from one style to another. Blocks are consistent and readable and the flow of the code is apparent. Coding style adds value for people who have to read your code after you’ve been hit by a bus. Remember that.
General Rules#
All source and header files should include a copy of the license.
Stick to a K&R coding style.
Space after keywords
Curly braces on new line following a function/subroutine.
Curly braces on same line as if/while/switch.
Prefer NSPR functions for file, string, memory allocation, etc. if at all possible.
All code should be peer reviewed before being checked in.
Functions and Subroutines#
functions should have the following form:
int foo(int bar)
{
}
NOT like this:
int foo(int bar) {
}
Statements#
if-else statements should have the following form:
\ *``condition``*\ ``) {
Balance the braces in the if and else in an if-else statement if either has only one line:
Always use braces, even if there’s only one line for both portions of an if-else statement:
Avoid last-return-in-else problem. Code should look like this:
NOT like this:
for, while and until statements should take a similar form:
switch statements:
Indentation#
Try to keep lines 80 characters or less.
Indentation is 4 spaces.
No tabs, use spaces. Your editor should take care of most of this but in patches tabs stick out like sore thumbs.
When wrapping lines, try to break it:
after a comma
before an operator
align the new line with the beginning of the expression at the same level in the previous line
if all else fails, just indent 8 spaces.
Variable Declarations#
One declaration per line is preferred.
instead of
`` int foo, bar;``
Initialize at declaration time when possible.
Declare variables at the beginning of a block to maintain C99 compatibility.
Comments#
Always use C-style comments in C programs, not C++-style comments (/* */ instead of //)
Each function should be preceeded with a block comment describing what the function is supposed to do.
Block comments should be preceeded by a blank line to set it apart. Line up the * characters in the block comment.
/*