Code style
Contents |
Control statements
Control statements have the left parenthesis next to the the keyword and a space following the parenthesis as well as one just before the right parenthesis. In addition, the braces appear on their own line, with the same indentation as the control statement's keyword.
if( logic || expression )
{
DoSomething();
}
One exception to this rule seems to be do-while loops where there is little consistency. I've seen,
do
{
Something();
}
while( condition );
as well as
do {
Something();
} while( condition );
Function calls have a space before the first argument and after the last. Most of the code puts spaces after the commas separating the arguments, but not all.
Lastly, when there is a function call (or any sort of parenthetical expression) inside another function call or control statement, the leading and trailing space is omitted.
foo( bar("hello") );
I am not positive, but I think that would also apply to the following.
if( foo(bar("hello")) ) { /* ... */ }
Switch statements
The case label should be indented as far as the switch keyword.
switch( x )
{
case 1:
foo();
break;
case 2:
bar();
// fall through
default:
baz();
}
Also note that if you intend the case to fall though, explicitly comment that because otherwise, it looks like a mistake.
Curly braces
There are a couple situations where braces are added for clarity:
- 1: dangling else
if( test1 ) if( test2 ) blah1(); else blah2();
becomes:
if( test1 )
{
if( test2 )
blah1();
else
blah2();
}
- 2: braces for if and else blocks should match
if( test2 )
blah1();
else
{
blah2();
blah3();
}
becomes:
if( test2 )
{
blah1();
}
else
{
blah2();
blah3();
}
Other
- Try to configure editors to use tabs, not spaces. Most of the code is formatted to not care too much about tab width; if you use spaces, you'll bake the tab width you're using into the code, so it'll look wrong to other people, and will usually end up with code using both tabs and spaces, leading to jigsaw indentation in other editors. (Code that aligns at spots other than the left edge is usually aligned for a 4-space tab stop.
- The best guideline is to read the other code, so you can notice when you're doing something unusual. A couple other things I've seen a lot:
/* Format block comments cleanly. This is fine, * ... */ /* * and this helps for large or important comments. In general, don't sign or * date comments unless it actually seems relevant; CVS does it for you. */
- Parenthesize expressions when needed, and when you're not sure, but don't go overboard--"if( (a == "b") && (c > d) && (e()) )" is just harder to read.
- Prefer "#if defined(X)" over "#ifdef X"--it gives an expression, which makes preprocessor statements more consistent with actual code.
