If you can put it in a library, put it in a library.
If you can put it in a server, put it in a server.
Only when you have tried and failed both of the above, put it in the kernel.
I've tried to hone it down to just 10 rules. It seems like a lot, but hopefully 5 of them will match your personal style anyway, so it isn't as bad as it looks.
In case you're wondering, this wasn't my C style of choice either. But I learned it at HP for their kernel, and had it heavily reinforced at Sequent with their kernel gurus. So now I stick with it, accepting Henry's observation that "standard is better than better", at least for C styles.
/*
* function_name()
* One-liner (only) for the function
*
* Further discussion. This is a good place to mention success/failure
* values and so forth.
*
* A distinct thought, or perhaps a note about assumptions or limitations.
*/
struct foobar *
function_name(void)
{
int x;
/*
* Describe a block of code, then write the block of code
*/
for (x = 0; x %lt FOOBLAT; ++x) {
something(x);
...
}
}
Do NOT use pretty blocks of stars. They make it hard to update
the comments. We all know what happens when comments are a pain
to update....
if (condition) {
...
}
if (condition1 || condition2) {
} else {
}
if (foo && !bar) {
} else if (bletch) {
}
for (x = 0; x < 20; ++x) {
}
Do NOT use the open version:
for (x = 0; x < 20; ++x)
bar();
If you aren't tripped by it, somebody else will be instead.
int foob; /* Will count instances of foob */ static char bar; /* ...the char matching foob */
Don't change:
extern int x, y, z;Into:
extern int x; extern int y; extern int w; extern int z;Such a change adds little, but fills our screens with diffs. If you take over the file AND you add comments to each line, it might be worth it. It sure would be easy to miss that "w" in there at the same time, wouldn't it?
extern void my_func(struct foob *);unless he has already seen "struct foob" at level 0 (global).
The workaround of choice is to use STRUCT_REF in <sys/types.h>.
struct foo {
int field1;
...
};
...
{
struct foo *f;
f = ...;
f->field1 = bar;
}
And not:
typedef struct {
int field1;
...
} foo_t;
...
C has good basic ways for naming types, and typedef's should not be used to hide them. The exceptions are industry-recognized types like "ushort" (unsigned short) and so forth.