C programming style comparison
This document is a little comparison of different people's way of writing C. It is only concerned with rather superficial syntactic style. Topics like variable naming and such are ignored.
NB: This is in no way comprehensive, only some features are discussed.
The people whose style I investigated and some code written by them are:
- Ken Thompson (ken)
- old UNIX /usr/sys/ken
- the Plan 9 C compiler
- the Go compiler: first commit
- Dennis Ritchie (dmr)
- old UNIX /usr/sys/dmr
- cc
- ed
- Brian Kernighan (bwk)
- Doug McIlroy (doug)
- m6
- a regex engine (note that this is actually C++)
- code on his website
- Rob Pike (rob)
- Tom Duff (td)
- code on his website
General
rob's earlier style is very much like td's, very compact with few spaces and (almost) no blank lines.
doug's style is quite compact as well but not quite as much, otherwise much like ken's.
ken's and dmr's style are very similar.
Indentation
Everybody indents with tabs.
Function return type
Style A:
type
function(args...)
Style B:
type function(args...)
Putting the return type on a separate line seems to be what most do. This allows for easy grepping like
grep '^function(' *.c
Also note that the return type was seldom used in the old days because it defaulted to int.
ken, dmr, doug and rob use style A.
bwk and td use style B. In the earliest C code, dmr uses style B as well.
Function braces
Style A:
function(args...)
{
}
Style B:
function(args...) {
}
(never mind the space in style B, see 'Spaces' below)
This is a bit complicated because a new way to define functions (taken from C++) was introduced with ANSI C. In that case the type declarations of the arguments go before the opening brace.
ken, dmr, bwk, doug and rob use style A.
td uses style B but doug also used style B for pre-ANSI functions
with type declarations.
Compound statement braces
Style A:
if(condition) {
}
Style B:
if(condition)
{
}
where 'if' stands for any similar keyword. (never mind the spaces, see 'Spaces' below)
Everybody uses style A.
Nobody regularly puts braces when they are unnecessary.
Spaces
Style A:
if (condition) {
}
Style B:
if(condition) {
}
Style C:
if(condition){
}
dmr and bwk use style A.
ken and doug use style B.
rob and td use style C.
TODO: spaces around operators
Newlines
td uses no blank lines at all.
td and dough write if/for/etc. statements in one line often.
Everybody but td (and early rob) separate functions by blank lines.
Most put a blank line after local variable declarations.
dmr uses blank lines between switch cases.
Most use blank lines to separate different parts of longer functions.