Skip to contentSkip to conversation

kernel guide to space (updated)

DISCUSSION Michael S. Tsirkin 9 participants 15 messages Jul 28, 2005 – Aug 1, 2005

lore
Share & tools
lore
#0 lore raw
Quoted 7 lines

I've been tasked with edicating some new hires on linux kernel coding style. While we have Documentation/CodingStyle, it skips detail that is supposed to be learned by example.

Since I've been burned by this a couple of times myself till I learned, I've put together a short list of rules complementing Documentation/CodingStyle. This list is attached, below.

Here's an updated version of the boring list. My thanks to everyone who commented on the first draft.

---

kernel guide to space AKA a boring list of rules
http://www.mellanox.com/mst/boring.txt

This text deals mostly with whitespace issues, hence the name.

Whitespace -- In computer science, a whitespace (or a whitespace character) is any character which does not display itself but does take up space.
From Wikipedia, the free encyclopedia.

1. Read Documentation/CodingStyle. Yes, it applies to you. When working on a specific driver/subsystem, try to follow the style of the surrounding codebase.

2. The last character on a line is never a whitespace
Get a decent editor and don't leave whitespace at the end of lines.
Documentation/CodingStyle

Whitespace issues:

3. Space rules for C

3a. Binary operators

	+ - / * %
	== !=  > < >= <= && ||
	& | ^ << >>
	= *= /= %= += -= <<= >>= &= ^= |=

	spaces around the operator
	a + b

3b. Unary operators

	! ~
	+ - *
	&

	no space between operator and operand
	*a

3c. * in types
space between type name and *
multiple * dont need additional space between them no space between * and its operand

struct foo **bar;

3d. Conditional
?:
spaces around both ? and :
a ? b : c

3e. sizeof
space after the operator
no space if the operand is in barces
sizeof *a
sizeof(b)

3f. Braces etc

	() [] -> .

	no space around any of these (but see 3h)
	foo(bar)

3g. Comma

	,
	space after comma, no space before comma
	foo, bar

3h. Semicolon

	;
	space after semicolon (e.g. in a for loop)
	no space before semicolon
	for (i = 0; i < 10; ++i)
		foo;

3i. if/else/do/while/for/switch

	space between if/else/do/while and following/preceeding
	statements/expressions, if any

	if (a) {
	} else {
	}

	do {
	} while (b);

3j. return
space between return and following expression, even if the operand is in barces return (a);

3k. Labels
goto and case labels should have a line of their own (possibly with a comment)
no space before colon in labels

int foobar()

{
	...
foolabel: /* short comment */
	foo();
}

4. Indentation rules for C
Use tabs, not spaces, for indentation. Tabs are 8 characters wide.

4a. Labels

	case labels should be indented same as the switch statement.
	statements occurring after a case label are indented by one level.

	switch (foo) {
	case foo:
		bar();
	default:
		break;
	}

4b. Global scope
Functions, type definitions/declarations, defines, global variables etc are global scope. Start them at the first character in a line (indent level 0).

static struct foo *foo_bar(struct foo *first, struct bar *second,

			   struct foobar* thirsd);

4c. Breaking long lines
Descendants are always substantially shorter than the parent and are placed substantially to the right.
Documentation/CodingStyle

Descendant must be indented at least to the level of the innermost compound expression in the parent. All descendants at the same level are indented the same.
if (foobar(..................................) +
raboof(................................) * barfoo(..........................)) {
}

5. Blank lines
One blank line between functions.

void foo()
{
}

/* comment */
void bar()
{
}

No more than one blank line in a row.
Last (or first) line in a file is never blank. Files end with a newline. gcc warns if this is not so.

Non-whitespace issues:

6. One-line statement does not need a {} block, so dont put it into one

	if (foo)
		bar;

7. Comments
Don't use C99 // comments.

8. Return codes

	Functions that return success/failure status, should use 0 for success,
	a negative value for failure.
	Error codes are in linux/errno.h .

	if (do_something()) {
		handle_error();
		return -EINVAL;
	}

	Functions that test a condition return 1 if condition is satisfied,
	0 if its not.

	if (is_condition())
		condition_true();

9. Data types
Standard linux types are in linux/types.h .
See also Linux Device Drivers, Third Edition,
Chapter 11: Data Types in the Kernel. http://lwn.net/images/pdf/LDD3/

9a. Integer types
int is the default integer type.
Use unsigned type if you perform bit operations (<<,>>,&,|,~). Use unsigned long if you have to fit a pointer into integer. long long is at least 64 bit wide on all platforms.
char is for ASCII characters and strings.
Use u8,u16,u32,u64 ... etc if you need an integer of a specific size.

9b. typedef
Using typedefs to hide the data type is generally discouraged. typedefs to function types are ok, since these can get very long.

typedef struct foo *foo_bar_handler(struct foo *first, struct bar *second,

				    struct foobar *thirsd);

Editor configuration:

9. The following is helpful with VIM

	set cinoptions=(0:0

Michael S. Tsirkin

Signature · 1 line
MST
#1 lore raw
Quoted 3 lines · Michael S. Tsirkin

7. Comments
Don't use C99 // comments.

I don't think this is correct. In fact, I remember a discussion where // was preferred for new code.

Cheers,
Dick Johnson
Penguin : Linux version 2.6.12 on an i686 machine (5537.79 BogoMips). Warning : 98.36% of all statistics are fiction.
.
I apologize for the following. I tried to kill it with the above dot :

****************************************************************
The information transmitted in this message is confidential and may be privileged. Any review, retransmission, dissemination, or other use of this information by persons or entities other than the intended recipient is prohibited. If you are not the intended recipient, please notify Analogic Corporation immediately - by replying to this message or by sending an email to [email protected] - and destroy all copies of this information, including any attachments, without reading or disclosing them.

Thank you.

#2 lore raw
Quoted 9 lines · linux-os (Dick Johnson)
Quoted 3 lines · Michael S. Tsirkin

7. Comments
Don't use C99 // comments.

I don't think this is correct. In fact, I remember a discussion where // was preferred for new code.

Ick...I hope not...

John

Signature · 2 lines
John W. Linville
[email protected]
#3 lore raw
In reply to Michael S. Tsirkin
Quoted 4 lines · Michael S. Tsirkin

9. The following is helpful with VIM

       set cinoptions=(0:0

And this will highlight whitespace damage:

highlight RedundantSpaces ctermbg=red guibg=red
match RedundantSpaces /\s\+$\| \+\ze\t/

Signature · 1 line
Dmitry
#4 lore raw
Quoted 8 lines
Quoted 3 lines

9. The following is helpful with VIM

       set cinoptions=(0:0

And this will highlight whitespace damage:

highlight RedundantSpaces ctermbg=red guibg=red
match RedundantSpaces /\s\+$\| \+\ze\t/

find linux -type f -print0 | xargs -0 egrep '[[:space:]]+$'

With wc -l, returns 132409* (wow, that's a lot of violations). Too bad that (e)grep does not support \s for space.

* Number might vary.

Jan Engelhardt

Signature · 1 line
| Alphagate Systems, http://alphagate.hopto.org/
#5 lore raw
In reply to Michael S. Tsirkin
Quoted 4 lines

3e. sizeof
space after the operator
no space if the operand is in barces

braces

Quoted 2 lines

3f. Braces etc

	() [] -> .

() parentheses (short form: parens)
[] square brackets
{} braces
<> dunno their name :p

Quoted 3 lines

3i. if/else/do/while/for/switch
space between if/else/do/while and following/preceeding statements/expressions, if any

Why this? if(a) {} is not any worse than if (a). I would make this an option.

Quoted 3 lines

3j. return
space between return and following expression, even if the operand is in barces

parentheses

Quoted 1 line
	return (a);

No unnecessary parentheses:

   return (3 + 7) * 5;
   return 1;

instead of

   return ((3 + 7) * 5);
   return (1);
Quoted 11 lines

3k. Labels
goto and case labels should have a line of their own (possibly with a comment)
no space before colon in labels

int foobar()

{
	...
foolabel: /* short comment */
	foo();
}

Would it be reasonable to say that the first column can be a space? Some editors (e.g. joe) list the function in some status bar and do that based on the fact that all C code in a function is indented, and only the function header is non-indented. Putting a label statement fools the algorithm. joe-bug or option for freedom?

Quoted 10 lines

4a. Labels

	case labels should be indented same as the switch statement.
	statements occurring after a case label are indented by one level.

	switch (foo) {
	case foo:
		bar();
	default:
		break;
	}

switch(foo) {

default: {
	int somevar = dosomething;
	break;
}

}

What now? You've got two }} after another.

Jan Engelhardt

#6 lore raw
Quoted 15 lines · Jan Engelhardt
Quoted 5 lines

3e. sizeof
space after the operator
no space if the operand is in barces

braces

Quoted 4 lines

3f. Braces etc

	() [] -> .
Quoted 5 lines

() parentheses (short form: parens)
[] square brackets
{} braces
<> dunno their name :p

angle brackets, it's all nicely explained at
http://en.wikipedia.org/wiki/Bracket

--
Joost

#7 lore raw
In reply to Jan Engelhardt

On Fri, Jul 29, 2005 at 09:40:14AM +0200, Jan Engelhardt wrote:
[snip]

Quoted 5 lines

Would it be reasonable to say that the first column can be a space? Some editors (e.g. joe) list the function in some status bar and do that based on the fact that all C code in a function is indented, and only the function header is non-indented. Putting a label statement fools the algorithm. joe-bug or option for freedom?

I'd definitely call that a joe-bug. Adding extra space for no good reason is just silly; for consistency we'd have to add a space for the case <foo>: labels also...

Regards: David

Signature · 3 lines
 /) David Weinehall <[email protected]> /) Northern lights wander      (\
//  Maintainer of the v2.0 kernel   //  Dance across the winter sky //
\)  http://www.acc.umu.se/~tao/    (/   Full colour fire           (/
#8 lore raw
Quoted 4 lines

I'd definitely call that a joe-bug. Adding extra space for no good reason is just silly; for consistency we'd have to add a space for the case <foo>: labels also...

No, the word "case" never starts at column 1 (counting from 1), but at least in column <minimalIndent>, where minimalIndent is the default indent for that particular piece of code.

Jan Engelhardt

#9 lore raw
Quoted 8 lines · Jan Engelhardt
Quoted 4 lines

I'd definitely call that a joe-bug. Adding extra space for no good reason is just silly; for consistency we'd have to add a space for the case <foo>: labels also...

No, the word "case" never starts at column 1 (counting from 1), but at least in column <minimalIndent>, where minimalIndent is the default indent for that particular piece of code.

Ehrm, yes, I'm perfectly aware of that. Note the "for consistency" in that sentence. If we add an extra space in front of the labels that have an indentation level of 0, we'd better do it with the labels that have an indentation level > 0 too.

Regards: David

Signature · 3 lines
 /) David Weinehall <[email protected]> /) Northern lights wander      (\
//  Maintainer of the v2.0 kernel   //  Dance across the winter sky //
\)  http://www.acc.umu.se/~tao/    (/   Full colour fire           (/
#10 lore raw
Quoted 5 lines

Ehrm, yes, I'm perfectly aware of that. Note the "for consistency" in that sentence. If we add an extra space in front of the labels that have an indentation level of 0, we'd better do it with the labels that have an indentation level > 0 too.

Labels at level > 0???

#11 lore raw
Quoted 7 lines · Jan Engelhardt
Quoted 5 lines

Ehrm, yes, I'm perfectly aware of that. Note the "for consistency" in that sentence. If we add an extra space in front of the labels that have an indentation level of 0, we'd better do it with the labels that have an indentation level > 0 too.

Labels at level > 0???

A case in a switch construct is a label.

Regards: David Weinehall

Signature · 3 lines
 /) David Weinehall <[email protected]> /) Northern lights wander      (\
//  Maintainer of the v2.0 kernel   //  Dance across the winter sky //
\)  http://www.acc.umu.se/~tao/    (/   Full colour fire           (/
#12 lore raw
Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

Ehrm, yes, I'm perfectly aware of that. Note the "for consistency" in that sentence. If we add an extra space in front of the labels that have an indentation level of 0, we'd better do it with the labels that have an indentation level > 0 too.

Labels at level > 0???

A case in a switch construct is a label.

Oh hm. I only meant "goto" labels.

#13 lore raw
In reply to Jan Engelhardt
Quoted 5 lines · Jan Engelhardt
Quoted 3 lines

3i. if/else/do/while/for/switch
space between if/else/do/while and following/preceeding statements/expressions, if any

Why this? if(a) {} is not any worse than if (a). I would make this an option.

please no, it's really better to have a unified CodingStyle. and "if (" is a lot more used than "if(".

$ grep -r "if (" linux-2.6.12/* | wc -l 
288027
$ grep -r "if(" linux-2.6.12/* | wc -l 
20682
Signature · 1 line
Vincent Hanquez
#14 lore raw
In reply to Jan Engelhardt
Quoted 5 lines · Jan Engelhardt
Quoted 3 lines

3i. if/else/do/while/for/switch
space between if/else/do/while and following/preceeding statements/expressions, if any

Why this? if(a) {} is not any worse than if (a).

Well it's harder to read (because it makes control constructs look more like function calls). And a bit uglier.

But anyway, coding styles are rarely about "worse" versus "better", they're about keeping things consistent so that it's easier to read code.

-Miles

Signature · 3 lines
Any man who is a triangle, has thee right, when in Cartesian Space, to
have angles, which when summed, come to know more, nor no less, than
nine score degrees, should he so wish.  [TEMPLE OV THEE LEMUR]