PATCH, RFC: 2.6 Documentation/Codingstyle
Here is Codingstyle updated.
Updates:
Kconfig
Clarifies:
Indentation
Adds:
Exiting functions
Parenthesis in expressions
Macros
Printk formatting
Cleans up:
Lagging spaces
Will update chapter numbering and spelling once contents OK.
Comments and suggestions are appreciated.
Regards
Michael
Documentation/CodingStyle renamed from Documentation/CodingStyle.mhf.orig +186 -56
@@ -1,42 +1,78 @@ - Linux kernel coding style + Linux kernel coding style This is a short document describing the preferred coding style for the linux kernel. Coding style is very personal, and I won't _force_ my views on anybody, but this is what goes for anything that I have to be able to maintain, and I'd prefer it for most other things too. Please -at least consider the points made here. +at least consider the points made here. First off, I'd suggest printing out a copy of the GNU coding standards, -and NOT read it. Burn them, it's a great symbolic gesture. +and NOT read it. Burn them, it's a great symbolic gesture. Anyway, here goes: Chapter 1: Indentation -Tabs are 8 characters, and thus indentations are also 8 characters. +Tabs are 8 characters, and thus indentations are also 8 characters. There are heretic movements that try to make indentations 4 (or even 2!) characters deep, and that is akin to trying to define the value of PI to -be 3. +be 3. Rationale: The whole idea behind indentation is to clearly define where a block of control starts and ends. Especially when you've been looking at your screen for 20 straight hours, you'll find it a lot easier to see -how the indentation works if you have large indentations. +how the indentation works if you have large indentations. Now, some people will claim that having 8-character indentations makes the code move too far to the right, and makes it hard to read on a 80-character terminal screen. The answer to that is that if you need more than 3 levels of indentation, you're screwed anyway, and should fix -your program. +your program. In short, 8-char indents make things easier to read, and have the added -benefit of warning you when you're nesting your functions too deep. -Heed that warning. +benefit of warning you when you're nesting your functions too deep. +Heed that warning. +Note that perhaps the most terrible way to write code is to put multiple +statements onto a single line: - Chapter 2: Placing Braces + if (condition) do_this; + +Outside of comments and except in Kconfig, spaces are never used for +indentation. + +Lagging spaces are deprecated. + + Chapter 2: Breaking long lines and strings + +Coding style is all about readability and maintainability using commonly +available tools. + +The limit on the length of lines is 80 columns and this is a hard limit. + +Statements longer than 80 columns will be broken into sensible chunks. +The beginning of a statement is the parent and further chunks are +descendent's. Descendent's are always shorter than the parent and +are placed substantially to the right. + +Long strings are broken into smaller strings too. + +void fun(int a, int b, int c) +{ + if (condition) + printk(KERN_WARNING "Warning this is a long printk with " + "3 parameters a: %u b: %u " + "c: %u \n", a, b, c); + else + next_statement; +} + +This method makes it very obvious that the printk is a single statement. + + + Chapter : Placing Braces The other issue that always comes up in C styling is the placement of braces. Unlike the indent size, there are few technical reasons to
@@ -59,7 +95,7 @@ Heretic people all over the world have claimed that this inconsistency is ... well ... inconsistent, but all right-thinking people know that (a) K&R are _right_ and (b) K&R are right. Besides, functions are -special anyway (you can't nest them in C). +special anyway (you can't nest them in C). Note that the closing brace is empty on a line of its own, _except_ in the cases where it is followed by a continuation of the same statement,
@@ -79,60 +115,60 @@ } else { .... } - -Rationale: K&R. + +Rationale: K&R. Also, note that this brace-placement also minimizes the number of empty (or almost empty) lines, without any loss of readability. Thus, as the supply of new-lines on your screen is not a renewable resource (think 25-line terminal screens here), you have more empty lines to put -comments on. +comments on. - Chapter 3: Naming + Chapter : Naming C is a Spartan language, and so should your naming be. Unlike Modula-2 and Pascal programmers, C programmers do not use cute names like ThisVariableIsATemporaryCounter. A C programmer would call that variable "tmp", which is much easier to write, and not the least more -difficult to understand. +difficult to understand. HOWEVER, while mixed-case names are frowned upon, descriptive names for global variables are a must. To call a global function "foo" is a -shooting offense. +shooting offense. GLOBAL variables (to be used only if you _really_ need them) need to have descriptive names, as do global functions. If you have a function that counts the number of active users, you should call that -"count_active_users()" or similar, you should _not_ call it "cntusr()". +"count_active_users()" or similar, you should _not_ call it "cntusr()". Encoding the type of a function into the name (so-called Hungarian notation) is brain damaged - the compiler knows the types anyway and can check those, and it only confuses the programmer. No wonder MicroSoft -makes buggy programs. +makes buggy programs. LOCAL variable names should be short, and to the point. If you have -some random integer loop counter, it should probably be called "i". +some random integer loop counter, it should probably be called "i". Calling it "loop_counter" is non-productive, if there is no chance of it being mis-understood. Similarly, "tmp" can be just about any type of -variable that is used to hold a temporary value. +variable that is used to hold a temporary value. If you are afraid to mix up your local variable names, you have another -problem, which is called the function-growth-hormone-imbalance syndrome. -See next chapter. +problem, which is called the function-growth-hormone-imbalance syndrome. +See next chapter. - - Chapter 4: Functions + + Chapter : Functions Functions should be short and sweet, and do just one thing. They should -fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24, -as we all know), and do one thing and do that well. +fit on one or two screens full of text (the ISO/ANSI screen size is 80x24, +as we all know), and do one thing and do that well. The maximum length of a function is inversely proportional to the complexity and indentation level of that function. So, if you have a conceptually simple function that is just one long (but simple) case-statement, where you have to do lots of small things for a lot of -different cases, it's OK to have a longer function. +different cases, it's OK to have a longer function. However, if you have a complex function, and you suspect that a less-than-gifted first-year high-school student might not even
@@ -140,41 +176,86 @@ maximum limits all the more closely. Use helper functions with descriptive names (you can ask the compiler to in-line them if you think it's performance-critical, and it will probably do a better job of it -than you would have done). +than you would have done). Another measure of the function is the number of local variables. They shouldn't exceed 5-10, or you're doing something wrong. Re-think the function, and split it into smaller pieces. A human brain can generally easily keep track of about 7 different things, anything more and it gets confused. You know you're brilliant, but maybe you'd like -to understand what you did 2 weeks from now. +to understand what you did 2 weeks from now. + +Centralized exiting of functions + +Albeit deprecated by some people, the goto statement is used frequently +by compilers in form of the unconditional jump instruction. + +The goto statement comes handy when a function exits from multiple +locations and some common work such as cleanup has to be done. + +The rationale is: + +- unconditional statements are easier to understand and follow +- nesting is reduced +- errors by not updating individual exit points when making modifications + are prevented +- saves the compiler work to optimize redundant code away ;) +int fun(int ) +{ + int result = 0; + char *buffer = kmalloc(SIZE); + + if (buffer == 0) { + result = -1; + goto out; + } + + if (condition1) { + while (loop1) { + ... + } + result = 1; + goto out; + } + if (condition2) { + while (loop2) { + ... + } + result = 2; + goto out; + } +out: + if (buffer) + kfree(buffer); + return result; +} - Chapter 5: Commenting + Chapter : Commenting Comments are good, but there is also a danger of over-commenting. NEVER try to explain HOW your code works in a comment: it's much better to write the code so that the _working_ is obvious, and it's a waste of -time to explain badly written code. +time to explain badly written code. -Generally, you want your comments to tell WHAT your code does, not HOW. +Generally, you want your comments to tell WHAT your code does, not HOW. Also, try to avoid putting comments inside a function body: if the function is so complex that you need to separately comment parts of it, you should probably go back to chapter 4 for a while. You can make small comments to note or warn about something particularly clever (or ugly), but try to avoid excess. Instead, put the comments at the head of the function, telling people what it does, and possibly WHY it does -it. +it. - Chapter 6: You've made a mess of it + Chapter : You've made a mess of it That's OK, we all do. You've probably been told by your long-time Unix user helper that "GNU emacs" automatically formats the C sources for you, and you've noticed that yes, it does do that, but the defaults it uses are less than desirable (in fact, they are worse than random typing - an infinite number of monkeys typing into GNU emacs would never -make a good program). +make a good program). So, you can either get rid of GNU emacs, or change it to use saner values. To do the latter, you can stick the following in your .emacs file:
@@ -201,33 +282,35 @@ everything is lost: use "indent". Now, again, GNU indent has the same brain-dead settings that GNU emacs -has, which is why you need to give it a few command line options. +has, which is why you need to give it a few command line options. However, that's not too bad, because even the makers of GNU indent recognize the authority of K&R (the GNU people aren't evil, they are just severely misguided in this matter), so you just give indent the -options "-kr -i8" (stands for "K&R, 8 character indents"). +options "-kr -i8" (stands for "K&R, 8 character indents"). "indent" has a lot of options, and especially when it comes to comment re-formatting you may want to take a look at the manual page. But -remember: "indent" is not a fix for bad programming. +remember: "indent" is not a fix for bad programming. - Chapter 7: Configuration-files + Chapter : Configuration-files -For configuration options (arch/xxx/config.in, and all the Config.in files), +For configuration options (arch/xxx/Kconfig, and all the Kconfig files), somewhat different indentation is used. -An indention level of 3 is used in the code, while the text in the config- -options should have an indention-level of 2 to indicate dependencies. The -latter only applies to bool/tristate options. For other options, just use -common sense. An example: - -if [ "$CONFIG_EXPERIMENTAL" = "y" ]; then - tristate 'Apply nitroglycerine inside the keyboard (DANGEROUS)' CONFIG_BOOM - if [ "$CONFIG_BOOM" != "n" ]; then - bool ' Output nice messages when you explode' CONFIG_CHEER - fi -fi +Help text is indented with 2 spaces. + +if CONFIG_EXPERIMENTAL + tristate CONFIG_BOOM + default n + help + Apply nitroglycerine inside the keyboard (DANGEROUS) + bool CONFIG_CHEER + depends on CONFIG_BOOM + default y + help + Output nice messages when you explode +endif Generally, CONFIG_EXPERIMENTAL should surround all options not considered stable. All options that are known to trash data (experimental write-
@@ -235,20 +318,20 @@ experimental options should be denoted (EXPERIMENTAL). - Chapter 8: Data structures + Chapter : Data structures Data structures that have visibility outside the single-threaded environment they are created and destroyed in should always have reference counts. In the kernel, garbage collection doesn't exist (and outside the kernel garbage collection is slow and inefficient), which -means that you absolutely _have_ to reference count all your uses. +means that you absolutely _have_ to reference count all your uses. Reference counting means that you can avoid locking, and allows multiple users to have access to the data structure in parallel - and not having to worry about the structure suddenly going away from under them just -because they slept or did something else for a while. +because they slept or did something else for a while. -Note that locking is _not_ a replacement for reference counting. +Note that locking is _not_ a replacement for reference counting. Locking is used to keep data structures coherent, while reference counting is a memory management technique. Usually both are needed, and they are not to be confused with each other.
@@ -264,3 +347,50 @@ Remember: if another thread can find your data structure, and you don't have a reference count on it, you almost certainly have a bug. + + Chapter : Parenthesis in expressions + +Complex expressions are easier to understand and maintain when extra +parenthesis are used. Here is an extreme example + +x = (((a + (b * c)) & d) | e) // would work also without any parenthesis + + + Chapter : Macros + +Macros defining constants are capitalized. + +#define CONSTANT 0x12345 + +CAPITALIZED macro names are appreciated but macros resembling functions +may be named in lower case. + +Macros with multiple statements should be enclosed in a do - while block. + +#define macrofun(a,b,c) \ +do { \ + if (a == 5) \ + do_this(b,c); \ + \ +} while (0) + +Macros defining expressions must enclose the expression in parenthesis +to reduce sideeffects. + +#define CONSTEXP (CONSTANT | 3) +#define MACWEXP(a,b) ((a) + (b)) + + + Chapter : printk formating + +Periods terminating kernel messages are deprecated + +Usage of the apostrophe <'> in kernel messages is deprecated + +Mis-spellings allowed in kernel messages are: + + dont, cant + +Printing numbers in parenthesis ie (%d) is deprecated + +
Documentation/CodingStyle line 392
Quoted 5 lines · Michael Frank
Documentation/CodingStyle renamed from Documentation/CodingStyle.mhf.orig +5
-0+Usage of the apostrophe <'> in kernel messages is deprecated + +Mis-spellings allowed in kernel messages are: + + dont, cant
I know some people prefer this, but is it really necessary? It makes kernel programmers look illiterate.
=============================
Tim Bird
Senior Staff Engineer
Sony Electronics
E-mail: [email protected]
=============================
On Fri, 13 Feb 2004 06:15:10 +0800 Michael Frank <[email protected]> wrote:
| +Centralized exiting of functions | + | +Albeit deprecated by some people, the goto statement is used frequently | +by compilers in form of the unconditional jump instruction. | + | +The goto statement comes handy when a function exits from multiple
comes in handy
| +locations and some common work such as cleanup has to be done.
| + Chapter : Parenthesis in expressions | + | +Complex expressions are easier to understand and maintain when extra | +parenthesis are used. Here is an extreme example | + | +x = (((a + (b * c)) & d) | e) // would work also without any parenthesis
parentheses (plural)
| +Macros defining expressions must enclose the expression in parenthesis parentheses
| +to reduce sideeffects.
side effects (or side-effects) (i.e., not one word)
| + Chapter : printk formating | + | +Periods terminating kernel messages are deprecated | + | +Usage of the apostrophe <'> in kernel messages is deprecated | + | +Mis-spellings allowed in kernel messages are: | + | + dont, cant | + | +Printing numbers in parenthesis ie (%d) is deprecated
I don't know that we reached any concensus on these. I think that these comments are just noise (IMO of course). I guess I'll spell out "do not" and "cannot".
--
~Randy
Quoted 9 lines · Tim Bird
Documentation/CodingStyle line 392
Quoted 5 lines · Michael Frank
Documentation/CodingStyle renamed from Documentation/CodingStyle.mhf.orig +5
-0+Usage of the apostrophe <'> in kernel messages is deprecated + +Mis-spellings allowed in kernel messages are: + + dont, cantI know some people prefer this, but is it really necessary? It makes kernel programmers look illiterate.
Agreed. If you don't like apostrophes you can spell it out as "do not" or "cannot".
Signature · 2 lines
Måns Rullgård [email protected]
Quoted 13 lines · Michael Frank
Documentation/CodingStyle renamed from Documentation/CodingStyle.mhf.orig +13
-0+ Chapter : Macros + +Macros defining constants are capitalized. + +#define CONSTANT 0x12345 + +CAPITALIZED macro names are appreciated but macros resembling functions +may be named in lower case. + +Macros with multiple statements should be enclosed in a do - while block. + +#define macrofun(a,b,c) \ +do { \
Documentation/CodingStyle line 381
Quoted 10 lines
Documentation/CodingStyle renamed from Documentation/CodingStyle.mhf.orig +10
-0+ if (a == 5) \ + do_this(b,c); \ + \ +} while (0) + +Macros defining expressions must enclose the expression in parenthesis +to reduce sideeffects. + +#define CONSTEXP (CONSTANT | 3) +#define MACWEXP(a,b) ((a) + (b))
Generally, enum and inline functions are preferable to the above.
Things to avoid when doing macros:
1) macros that affect control flow:
#define FOO(x) do {if (blah(x) < 0) return -EBUGGERED;} while(0)
is _not_ a good idea. It looks like a function call; don't break the internal parsers of those who will read the code.
2) macros that depend on having a local variable with magic name:
#define FOO(val) bar(index, val)
might look like a good thing, but it's confusing as hell when one reads the code and it's prone to breakage from seemingly innocent changes.
3) macros with arguments that are used as l-values: FOO(x) = y; will
bite you if somebody e.g. turns FOO into inlined function.
Quoted 9 lines · Tim Bird
Documentation/CodingStyle line 392
Quoted 5 lines · Michael Frank
Documentation/CodingStyle renamed from Documentation/CodingStyle.mhf.orig +5
-0+Usage of the apostrophe <'> in kernel messages is deprecated + +Mis-spellings allowed in kernel messages are: + + dont, cantI know some people prefer this, but is it really necessary? It makes kernel programmers look illiterate.
Really - why is this backwards. Why deprecate ' and encourage bad punctuation?
Documentation/CodingStyle line 39
Quoted 2 lines · Michael Frank
Documentation/CodingStyle renamed from Documentation/CodingStyle.mhf.orig +2
-0+Note that perhaps the most terrible way to write code is to put multiple +statements onto a single line:
If you can't manage Linus's sense of humor, go for something simple that doesn't call attention to itself; e.g., "Don't put multiple statements on a single line:"
Quoted 1 line
+Lagging spaces are deprecated.
Does everyone know immediately what "Lagging spaces" means? "Trailing spaces" seem to be more common usage. "Don't leave whitespace at the end of lines" might be clearest.
Documentation/CodingStyle line 57
Quoted 5 lines
Documentation/CodingStyle renamed from Documentation/CodingStyle.mhf.orig +5
-0+The limit on the length of lines is 80 columns and this is a hard limit. + +Statements longer than 80 columns will be broken into sensible chunks. +The beginning of a statement is the parent and further chunks are +descendent's. Descendent's are always shorter than the parent and
The last vowel of descendant (in the sense you're using it) is an "a", and its plural is descendants.
Surely this section is overkill for a discussion of line lengths. The current document has the advantage of being short.
Quoted 1 line
+Centralized exiting of functions
That, on the other hand, is something worth documenting.
Documentation/CodingStyle line 356
Quoted 4 lines
Documentation/CodingStyle renamed from Documentation/CodingStyle.mhf.orig +4
-0+Complex expressions are easier to understand and maintain when extra +parenthesis are used. Here is an extreme example + +x = (((a + (b * c)) & d) | e) // would work also without any parenthesis
Ugh. This isn't LISP here. The number of operators in C does make keeping track of precedence tricky, but readers should be expected to know a few things (like that * is higher precedence than +). I'd just leave out this discussion entirely. CodingStyle is not, I think, meant to be a complete C style guide.
Documentation/CodingStyle line 394
Quoted 5 lines
Documentation/CodingStyle renamed from Documentation/CodingStyle.mhf.orig +3
-0+Periods terminating kernel messages are deprecated +Usage of the apostrophe <'> in kernel messages is deprecated +Printing numbers in parenthesis ie (%d) is deprecated
I find the "X is deprecated" construction a little awkward. In any case it's overused here.
--Bruce Fields
Quoted 7 lines · Randy.Dunlap
On Fri, 13 Feb 2004 06:15:10 +0800 Michael Frank <[email protected]> wrote:
| +Printing numbers in parenthesis ie (%d) is deprecated
I don't know that we reached any concensus on these. I think that these comments are just noise (IMO of course). I guess I'll spell out "do not" and "cannot".
You also didn't correct the last incorrect use of "parenthesis" when he meant "parentheses." Of course, one would hope by this point in your email he'd have ... gotten the point.
Signature · 2 lines
Alex Goddard agoddard at purdue dot edu
Quoted 11 lines
| +Usage of the apostrophe <'> in kernel messages is deprecated | + | +Mis-spellings allowed in kernel messages are: | + | + dont, cant | + | +Printing numbers in parenthesis ie (%d) is deprecatedI don't know that we reached any concensus on these. I think that these comments are just noise (IMO of course). I guess I'll spell out "do not" and "cannot".
Precisely - since are we supposed to now accept "Id" as "I'd", "Ill" as "I'll", etc? What about cases where the apostrophe can't be decontracted
- like Fred's source code - how do we remove the apostrophe there? Change it to Freds? That will likely in some cases change the meaning: it's/its, etc to name just one.
This is pointless - you won't manage to remove all single quotes anyway.
One side considers "dont" and "cant" to look like someone illiterate was typing and will do everything in their power to keep the quotes in and perceived spelling errors out.
The other side obviously considers any single quote to be a source of great eye discomfort will try for the opposite effect.
This is in many ways a pointless debate - you won't manage to convince people either one nor the other way.
These are comments - they can and often do contain 8-bit characters anyway
- containing single quotes is not that great a problem - they already contain single backslashes - or should we escape those as well?
Cheers,
MaZe.
Re: PATCH, RFC: Version 2 of 2.6 Codingstyle
In reply to Michael FrankThank you for your feedback which has been incorporated into this version.
Changes:
Appreciate that kernel developers are literate
Added sggestions on inlines and enums
Dropped chapter on parentheses
Shortened things
Some fixes
Here is a diff against the previous version and a diff against the current in-kernel version is thereafter.
Regards
Michael
CodingStyle renamed from CodingStyle.mhf.orig.1 +48 -41
@@ -35,29 +35,27 @@ benefit of warning you when you're nesting your functions too deep. Heed that warning. -Note that perhaps the most terrible way to write code is to put multiple -statements onto a single line: +Don't put multiple statements on a single line unless you have +something to hide: if (condition) do_this; + do_something_everytime; Outside of comments and except in Kconfig, spaces are never used for indentation. -Lagging spaces are deprecated. +Don't leave whitespace at the end of lines. + Chapter 2: Breaking long lines and strings Coding style is all about readability and maintainability using commonly available tools. -The limit on the length of lines is 80 columns and this is a hard limit. - Statements longer than 80 columns will be broken into sensible chunks. -The beginning of a statement is the parent and further chunks are -descendent's. Descendent's are always shorter than the parent and -are placed substantially to the right. - -Long strings are broken into smaller strings too. +Descendant's are always shorter than the parent and are placed substantially +to the right. The same applies to function headers with a long argument list. +Long strings are as well broken into smaller strings. void fun(int a, int b, int c) {
@@ -65,12 +63,10 @@ printk(KERN_WARNING "Warning this is a long printk with " "3 parameters a: %u b: %u " "c: %u \n", a, b, c); - else + else next_statement; } -This method makes it very obvious that the printk is a single statement. - Chapter : Placing Braces
@@ -190,7 +186,7 @@ Albeit deprecated by some people, the goto statement is used frequently by compilers in form of the unconditional jump instruction. -The goto statement comes handy when a function exits from multiple +The goto statement comes in handy when a function exits from multiple locations and some common work such as cleanup has to be done. The rationale is:
@@ -218,13 +214,7 @@ result = 1; goto out; } - if (condition2) { - while (loop2) { - ... - } - result = 2; - goto out; - } + ... out: if (buffer) kfree(buffer);
@@ -348,23 +338,20 @@ Remember: if another thread can find your data structure, and you don't have a reference count on it, you almost certainly have a bug. - Chapter : Parenthesis in expressions - -Complex expressions are easier to understand and maintain when extra -parenthesis are used. Here is an extreme example -x = (((a + (b * c)) & d) | e) // would work also without any parenthesis + Chapter : Inlines, Enums and Macros - - Chapter : Macros - -Macros defining constants are capitalized. +Macros defining constants and values in enums are capitalized. #define CONSTANT 0x12345 +Enums are preferred when defining several related constants. + CAPITALIZED macro names are appreciated but macros resembling functions may be named in lower case. +Generally, inline functions are preferable to macros resembling functions. + Macros with multiple statements should be enclosed in a do - while block. #define macrofun(a,b,c) \
@@ -374,23 +361,44 @@ \ } while (0) -Macros defining expressions must enclose the expression in parenthesis -to reduce sideeffects. +Things to avoid when doing macros: -#define CONSTEXP (CONSTANT | 3) -#define MACWEXP(a,b) ((a) + (b)) +1) macros that affect control flow: + +#define FOO(x) \ + do { \ + if (blah(x) < 0) \ + return -EBUGGERED; \ + } while(0) + +is a _very_ bad idea. It looks like a function call but exits the "calling" +function; don't break the internal parsers of those who will read the code. + +2) macros that depend on having a local variable with magic name: +#define FOO(val) bar(index, val) - Chapter : printk formating +might look like a good thing, but it's confusing as hell when one reads the +code and it's prone to breakage from seemingly innocent changes. + +3) macros with arguments that are used as l-values: FOO(x) = y; will +bite you if somebody e.g. turns FOO into inlined function. + +4) forgetting about sideeffects. Macros defining expressions must enclose the +expression in parenthesis. Note that this does not eliminate all side effects. + +#define CONSTEXP (CONSTANT | 3) +#define MACWEXP(a,b) ((a) + (b)) -Periods terminating kernel messages are deprecated -Usage of the apostrophe <'> in kernel messages is deprecated + Chapter : Printing kernel messages -Mis-spellings allowed in kernel messages are: +Kernel developers like to be seen as literate. Do mind the spelling +of kernel messages to make a good impression. Do not use crippled +words like "dont" and use "do not" or "don't" instead. - dont, cant +Kernel messages do not have to be terminated with a period. -Printing numbers in parenthesis ie (%d) is deprecated +Printing numbers in parenthesis (%d) adds no value and should be avoided. ----------------------------------------------------
Diff against current.
CodingStyle renamed from CodingStyle.mhf.orig +194 -56
400 lines not on this page · raw message
Quoted 3 lines · On 12-Feb-2004 Michael Frank wrote:
Here is Codingstyle updated.
+The limit on the length of lines is 80 columns and this is a hard limit.
Well, I think this requirement is a bit silly IMHO. How many of us do usually code in a 80x25 terminal screen nowadays ?
--
Giuliano.
Quoted 10 lines · Giuliano Pochini
Quoted 3 lines · On 12-Feb-2004 Michael Frank wrote:
Here is Codingstyle updated.
+The limit on the length of lines is 80 columns and this is a hard limit.
Well, I think this requirement is a bit silly IMHO. How many of us do usually code in a 80x25 terminal screen nowadays ?
"I think the 90x25 requirement is silly"
"I think the 100x25 requirement is silly"
And so it goes. You get into an xterm arms race wherein everyone has to make their terminal as wide as the widest guy so anyone can get any work done.
Yes, 80 cols sucks and the world would be a better place had CodingStyle mandated 96 columns five years ago. But it didn't happen.
Quoted 8 lines · Giuliano Pochini
Quoted 3 lines · On 12-Feb-2004 Michael Frank wrote:
Here is Codingstyle updated.
+The limit on the length of lines is 80 columns and this is a hard limit.
Well, I think this requirement is a bit silly IMHO. How many of us do usually code in a 80x25 terminal screen nowadays ?
I do.
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 (/
Quoted 7 lines · Andrew Morton
Quoted 6 lines · Giuliano Pochini
Quoted 3 lines · On 12-Feb-2004 Michael Frank wrote:
Here is Codingstyle updated.
+The limit on the length of lines is 80 columns and this is a hard limit.
Sorry, I "shortened" that line away and will add it again.
Quoted 3 lines
Quoted 3 lines
Well, I think this requirement is a bit silly IMHO. How many of us do usually code in a 80x25 terminal screen nowadays ?
I still use 80 wide but with many more lines. I tend to be sloppy about code extending beyond 80, which I shall change ;)
Also bear in mind that the fundamental arguments for 80 columns are not related to (display) hardware capabilities, but related to clarity of code.
Quoted 7 lines
Quoted 1 line
"I think the 90x25 requirement is silly"
"I think the 100x25 requirement is silly"
Quoted 7 lines
And so it goes. You get into an xterm arms race wherein everyone has to make their terminal as wide as the widest guy so anyone can get any work done.
Yes, 80 cols sucks and the world would be a better place had CodingStyle mandated 96 columns five years ago. But it didn't happen.
As to "five years ago", what about review the coding style situation before starting 2.7:
In view of better hardware, increasing linelength a little to 96 could be considered without increasing the number of indentation levels.
Perhaps consider deprecating function-like macros as inline technology is much improved.
...
Re: PATCH, RFC: Version 2 of 2.6 Codingstyle
In reply to Michael FrankOn Fri, Feb 13, 2004 at 04:49:30PM +0800, Michael Frank wrote:
-fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24, +fit on one or two screens full of text (the ISO/ANSI screen size is 80x24,
Not an improvement.
Quoted 13 lines · Michael Frank
Quoted 5 lines · Andrew Morton
Yes, 80 cols sucks and the world would be a better place had CodingStyle mandated 96 columns five years ago. But it didn't happen.
As to "five years ago", what about review the coding style situation before starting 2.7:
In view of better hardware, increasing linelength a little to 96 could be considered without increasing the number of indentation levels.
I hope not, I usually use 80 columns. Email's using 80 columns. And lines start becoming difficult for the eyes to follow as they get longer. Maybe this isn't so much a problem with C code due to indentation and the sparseness of the lines.
Quoted 19 lines · Nick Piggin
Quoted 8 lines · Michael Frank
Quoted 5 lines · Andrew Morton
Yes, 80 cols sucks and the world would be a better place had CodingStyle mandated 96 columns five years ago. But it didn't happen.
Quoted 7 lines
As to "five years ago", what about review the coding style situation before starting 2.7:
In view of better hardware, increasing linelength a little to 96 could be considered without increasing the number of indentation levels.
Quoted 5 lines
I hope not, I usually use 80 columns. Email's using 80 columns. And lines start becoming difficult for the eyes to follow as they get longer. Maybe this isn't so much a problem with C code due to indentation and the sparseness of the lines.
Just for consideration and nesting should _not_ be increased ;)
80 is quite OK but has not much margin and is asking for more lines times with nesting of 3.
0 1 2 3 4 |<81
printk(KERN_WARNING "Warning this is a long printk with " "3 parameters a: %u b: %u " "c: %u \n", a, b, c); next_statement; printk(KERN_WARNING "Warning this is a long printk with " "3 parameters a: %u b: %u "c: %u \n", a, b, c); next_statement;
96 is not excessive and will reduce linecount and often makes things more readable.
0 1 2 3 4 |<97
printk(KERN_WARNING "Warning this is a long printk with 3 parameters " "a: %u b: %u "c: %u \n", a, b, c); next_statement;
Re: PATCH, RFC: Version 2 of 2.6 Codingstyle
In reply to Andries BrouwerCodingStyle line 160
Quoted 4 lines · Andries Brouwer
On Fri, Feb 13, 2004 at 04:49:30PM +0800, Michael Frank wrote:
CodingStyle renamed from CodingStyle.mhf.orig +1
-1-fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24, +fit on one or two screens full of text (the ISO/ANSI screen size is 80x24,
Can even be "screensful": vide spoonful->spoonsful.
Quoted 2 lines
Not an improvement.
Nikita.
Quoted 4 lines · Giuliano Pochini
Quoted 1 line
+The limit on the length of lines is 80 columns and this is a hard limit.
Well, I think this requirement is a bit silly IMHO. How many of us do usually code in a 80x25 terminal screen nowadays ?
I do. (That is, 80xN with N in 24..60 or so.)
The 80 here has a pedagogical and a practical purpose.
The practical one is that it makes sure that everybody can read the source. The pedagogical is to invite you to arrange the code in a different way if you are nesting too deeply or your expressions are too complicated.
There is also ergonomics. There is a reason newspapers do not print text across the full width of the page - it would be very difficult to read. There is an optimal column width. One might fight over the exact value of the optimum, but 80 columns is not a bad choice.
Andries
Quoted 8 lines · Andries Brouwer
Quoted 4 lines · Giuliano Pochini
Quoted 1 line
+The limit on the length of lines is 80 columns and this is a hard limit.
Well, I think this requirement is a bit silly IMHO. How many of us do usually code in a 80x25 terminal screen nowadays ?
I do. (That is, 80xN with N in 24..60 or so.)
So do I. I like to be able to fit a few xterms or emacsen side by side on the screen. I can't do that if I make them too wide.
Signature · 2 lines
Måns Rullgård [email protected]
Quoted 14 lines · Andries Brouwer
Quoted 5 lines · Giuliano Pochini
Quoted 2 lines
+The limit on the length of lines is 80 columns and this is a hard limit.
Well, I think this requirement is a bit silly IMHO. How many of us do usually code in a 80x25 terminal screen nowadays ?
I do. (That is, 80xN with N in 24..60 or so.)
The 80 here has a pedagogical and a practical purpose.
The practical one is that it makes sure that everybody can read the source. The pedagogical is to invite you to arrange the code in a different way if you are nesting too deeply or your expressions are too complicated.
Quoted 4 lines
There is also ergonomics. There is a reason newspapers do not print text across the full width of the page - it would be very difficult to read. There is an optimal column width. One might fight over the exact value of the optimum, but 80 columns is not a bad choice.
This would be true if not for indenting. A program is not a newspaper. I doubt the lenght of text, excluding the indent is longer than 80 chars
very often.... With 80 columns and indenting code looks ugly.
Ed Tomlinson
Quoted 2 lines · Andrew Morton
Yes, 80 cols sucks and the world would be a better place had CodingStyle mandated 96 columns five years ago. But it didn't happen.
Well, IBM had tried that once (System/3), but it didn't stick ;-)
Quoted 6 lines · Andries Brouwer
I do. (That is, 80xN with N in 24..60 or so.)
The 80 here has a pedagogical and a practical purpose.
The practical one is that it makes sure that everybody can read the source. The pedagogical is to invite you to arrange the code in a different way if you are nesting too deeply or your expressions are too complicated.
Deeply nested doesn't mean unreadable or badly structured. 1 tab in the function, 1tab a switch, 1 if, 1 for, 1 if and you have already lost half of the available space. It's not difficult to find lines compressed towards the 79th column in the kernel sources.
I propose to change "hard limit" to "soft limit" to avoid things like this:
rc=idefloppy_begin_format(drive, inode,
file,
(int *)arg);IMO we should try to keep function calls on the same line. btw it's only a matter of taste and the compiler accepts ugly code too :))
Quoted 3 lines
There is also ergonomics. There is a reason newspapers do not print text across the full width of the page - it would be very difficult to read.
Code has only one instruction per line.
--
Giuliano.
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Quoted 6 lines · On Fri, 13 Feb 2004 14:55:13 +0100 (CET) Giuliano Pochini <[email protected]>…
Quoted 4 lines
The 80 here has a pedagogical and a practical purpose.
The practical one is that it makes sure that everybody can read the source. The pedagogical is to invite you to arrange the code in a different way if you are nesting too deeply or your expressions are too complicated.Deeply nested doesn't mean unreadable or badly structured.
I think you're really wrong since "deeply nested" means exactly "unreadable and badly structured" and you could easily realize it by simply spending ~10 hours per day coding and/or taking a look at the code written by someone which is not you. A simple use of inline functions and a previous thinking about what you're going to write could easily solve all problems.
Quoted 8 lines
1 tab in the function, 1tab a switch, 1 if, 1 for, 1 if and you have already lost half of the available space. It's not difficult to find lines compressed towards the 79th column in the kernel sources. I propose to change "hard limit" to "soft limit" to avoid things like this:
rc=idefloppy_begin_format(drive, inode, file, (int *)arg);
No one is saying this line of code is the best one could imagine... have you ever thought that maybe anything "floating around" that code line could be written in a not-well structured way?
Quoted 2 lines
IMO we should try to keep function calls on the same line. btw it's only a matter of taste and the compiler accepts ugly code too :))
A compiler should do it, a maintainer IMHO should not for a really simple
reason: readability (which in most cases means maintainability too).
Quoted 5 lines
Quoted 3 lines
There is also ergonomics. There is a reason newspapers do not print text across the full width of the page - it would be very difficult to read.
Code has only one instruction per line.
Not a good point.
Regards.
- --
Angelo Dell'Aera 'buffer'
Antifork Research, Inc. http://buffer.antifork.org
PGP information in e-mail header
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
iD8DBQFALOC+pONIzxnBXKIRApWFAJ9JjvwcnfgPz1V5bvfwzjE2Xb7c5wCfWdOH s9fGQvTBV3iEaZQdy8tp8nQ=
=v4FT
-----END PGP SIGNATURE-----
Quoted 6 lines · On 13-Feb-2004 Angelo Dell'Aera wrote:
Quoted 1 line
Deeply nested doesn't mean unreadable or badly structured.
I think you're really wrong since "deeply nested" means exactly "unreadable and badly structured" and you could easily realize it by simply spending ~10 hours per day coding and/or taking a look at the code written by someone which is not you.
Deeply means 4-5 levels in this case, not 20. The example I posted was only 3 (plus the one of the function) levels down.
--
Giuliano.
Quoted 5 lines · Angelo Dell'Aera
I think you're really wrong since "deeply nested" means exactly "unreadable and badly structured" and you could easily realize it by simply spending ~10 hours per day coding and/or taking a look at the code written by someone which is not you. A simple use of inline functions and a previous thinking about what you're going to write could easily solve all problems.
It might help, but a blind belief that "if I inline things it will all be better" won't solve all the problems. In particular, for the example you replied to:
Quoted 2 lines
Quoted 2 lines
1 tab in the function, 1tab a switch, 1 if, 1 for, 1 if and you have already lost half of the available space.
you may very well be advocating the inlining of a 3 or 4 line code segment, and moving it to someplace far away in the .c file. Certainly the compiler can probably manage to generate the same code, but now you're condemning the next person who reads this code to go flipping back and forth through the file to find the only-used-once and unfamiliar function to see what this for(;;) loop does.
Oh, and it gets very ugly if you have this:
switch
if (foo) {
for (ptr=first; ptr->next!=NULL; prt->next) {
if (!(ptr->somedata))
goto have_to_drop_dead_now;
/* more code that deals with ptr-> here */Creating an inline function for that is going to be.. interesting. :)
Quoted 5 lines · Giuliano Pochini
I propose to change "hard limit" to "soft limit" to avoid things like this:
rc=idefloppy_begin_format(drive, inode, file, (int *)arg);
To avoid such things, we'd better
a) note that idefloppy_begin_format() ignores its second and third
arguments and thus shouldn't have them at all (done in 2.6)
b) note that we are within
if (...) {
...
return -EBUSY;
} else {
...
our call
...
}
and thus can trim one indent level. (done in 2.6)
c) note that we are within
{
idefloppy_floppy_t *floppy = drive->driver_data;
...
our call
...
}
and compound operator is needed only to because of that declaration. At
the same time, we already have
idefloppy_floppy_t *floppy = drive->driver_data;in the beginning of function and neither drive nor drive->driver_data can change between those declarations. IOW, declaration in the compound statement can be dropped and statement itself - opened. (done in 2.6)
d) note that it's static, so "idefloppy_" prefix is plain and simple
idiocy.
e) note that rc = begin_format(drive, (int *)arg);
fits on the line just fine and is far more readable than crap above, with or without linewrap.
Next example, please?
While we are at it,
if (drive->usage > 1) {
/* Don't format if someone is using the disk */
several lines above is broken by design -
fd = open("/dev/hdc", O_RDWR);
if (fork() == 0)
write(fd, big_buffer, sizeof(big_buffer);
else
ioctl(fd, IDEFLOPPY_IOCTL_FORMAT_START, &args);
exit(0);will cheerfully pass that check and start format while the drive is very much in use. Driver (and hardware) will not be happy.
ioctl(2) - Just Say No...
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Quoted 9 lines · On Fri, 13 Feb 2004 10:48:14 -0500 [email protected] wrote:
Quoted 5 lines
I think you're really wrong since "deeply nested" means exactly "unreadable and badly structured" and you could easily realize it by simply spending ~10 hours per day coding and/or taking a look at the code written by someone which is not you. A simple use of inline functions and a previous thinking about what you're going to write could easily solve all problems.
It might help, but a blind belief that "if I inline things it will all be better" won't solve all the problems. In particular, for the example you replied to:
I'm not saying "just inline anything and you'll solve problems". I'm saying that if your design is well done and you consider the availability of the inlines your code will surely be better. And maybe you wouldn't need to discuss why the current limit is 80...
Quoted 9 lines
Quoted 2 lines
Quoted 2 lines
1 tab in the function, 1tab a switch, 1 if, 1 for, 1 if and you have already lost half of the available space.
you may very well be advocating the inlining of a 3 or 4 line code segment, and moving it to someplace far away in the .c file. Certainly the compiler can probably manage to generate the same code, but now you're condemning the next person who reads this code to go flipping back and forth through the file to find the only-used-once and unfamiliar function to see what this for(;;) loop does.
I prefer going flipping back and forth rather than reading an uncomprehensible source. Simpler functions may be analyzed and debugged in a faster way. If you dislike going back and forth by hand some tools could help you (think about cscope). Taking a look at the kernel code it's easy to realize I'm not the only one thinking so...
Moreover, if you take a look at the kernel code you'll realize that well written code usually defines inlines you really shouldn't need to read since their names are quite often self-explaining. Taken from CodingStyle "If you have a function that counts the number of active users, you should call that "count_active_users()" or similar, you should _not_ call it "cntusr()"."
Please don't think simply at those who are reading the code. Think about the persons which wrote that code which want to remember what they did two weeks before...
Quoted 10 lines
Oh, and it gets very ugly if you have this:
switch if (foo) { for (ptr=first; ptr->next!=NULL; prt->next) { if (!(ptr->somedata)) goto have_to_drop_dead_now; /* more code that deals with ptr-> here */Creating an inline function for that is going to be.. interesting. :)
You could create a lot of examples where it's difficult to create an inline.. but they're just examples! There are a lot of ways for writing the same code and maybe if your example was taken from a real-life code it could be written in a different and more easy-to-read manner.
Regards.
- --
Angelo Dell'Aera 'buffer'
Antifork Research, Inc. http://buffer.antifork.org
PGP information in e-mail header
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
iD8DBQFALP13pONIzxnBXKIRAsddAJ0UkI8RkgyVsCe9CEgCAq3OjT3X6wCfZFOE b7fPjRZw+/Dfv05H+aO6tpw=
=KXgO
-----END PGP SIGNATURE-----
Quoted 1 line · Angelo Dell'Aera
-----BEGIN PGP SIGNED MESSAGE-----
Quoted 3 lines · you
Quoted 3 lines
Quoted 3 lines
which is not you. A simple use of inline functions and a previous thinking
about what you're going to write could easily solve all problems.
And now:
Quoted 3 lines
I'm not saying "just inline anything and you'll solve problems". I'm saying that if your design is well done and you consider the availability of the inlines your code will surely be better. And maybe you wouldn't need to discu
ss
Quoted 1 line
why the current limit is 80...
I didn't claim it didn't help. I objected to your claim that it would "easily solve all problems". It help, but isn't a cure-all.
(Sorry, I'm just touchy - after a quarter of a century of hearing "fixes everything" claims for everything from "structured programming" to "extreme programming", I tend to take extreme objection.. :)
Quoted 4 lines
You could create a lot of examples where it's difficult to create an inline.. but they're just examples! There are a lot of ways for writing the same code and maybe if your example was taken from a real-life code it could be written in a different and more easy-to-read manner.
4 tabs:
[/usr/src/linux-2.6.3-rc2-mm1]2 find . -name '*.[ch]' | xargs grep '\t\t\t\tgoto' | wc -l
827
And 5:
[/usr/src/linux-2.6.3-rc2-mm1]2 find . -name '*.[ch]' | xargs grep '\t\t\t\t\tgoto' | wc -l
183
Feel free to start fixing. :)
Re: PATCH, RFC: Version 2 of 2.6 Codingstyle
In reply to Michael FrankOn Fri, 13 Feb 2004 16:49:30 +0800 Michael Frank <[email protected]> wrote:
| --- Documentation/CodingStyle.mhf.orig.1 2004-02-13 06:05:11.000000000 +0800 | +++ Documentation/CodingStyle 2004-02-13 16:42:07.000000000 +0800 | | Chapter 2: Breaking long lines and strings | | - | -Long strings are broken into smaller strings too. | +Descendant's are always shorter than the parent and are placed substantially
* Descendants (plural, not possessive)
| +to the right. The same applies to function headers with a long argument list. | +Long strings are as well broken into smaller strings.
| +4) forgetting about sideeffects. Macros defining expressions must enclose the
* <sideeffects> : it's still not one word.
| +expression in parenthesis. Note that this does not eliminate all side effects.
* parentheses
--
~Randy
Quoted 19 lines · Michael Frank
Documentation/CodingStyle renamed from Documentation/CodingStyle.mhf.orig +19
-0+int fun(int ) +{ + int result = 0; + char *buffer = kmalloc(SIZE); + + if (buffer == 0) { + result = -1; + goto out; + } + + if (condition1) { + while (loop1) { + ... + } + result = 1; + goto out; + } + if (condition2) { + while (loop2) {
Documentation/CodingStyle line 232
Quoted 10 lines
Documentation/CodingStyle renamed from Documentation/CodingStyle.mhf.orig +10
-0+ ... + } + result = 2; + goto out; + } +out: + if (buffer) + kfree(buffer); + return result; +}
This is a bit of a nitpick, but if you're going to give a code example in a file titled "Coding style" I'd recommend two changes:
1 - kfree already checks for null, so checking for null before calling
kfree is pointless.
2 - I personally think testing pointers against an integer is bad style, so
I'd prefer to see the original test changed to "if (!buffer)" or less-preferably "if (buffer == NULL)".
Documentation/CodingStyle line 375
Quoted 8 lines
Documentation/CodingStyle renamed from Documentation/CodingStyle.mhf.orig +8
-0+Macros with multiple statements should be enclosed in a do - while block. + +#define macrofun(a,b,c) \ +do { \ + if (a == 5) \ + do_this(b,c); \ + \ +} while (0)
Enclosing macros in a do-while block is sound advice, but the above is an example of something that should be an inline function.
-Kevin
Signature · 4 lines
--------------------------------------------------------------------- | Kevin O'Connor "BTW, IMHO we need a FAQ for | | [email protected] 'IMHO', 'FAQ', 'BTW', etc. !" | ---------------------------------------------------------------------
Quoted 2 lines · Kevin O'Connor
1 - kfree already checks for null, so checking for null before calling
kfree is pointless.
As anybody who's chased a 'null pointer dereference' OOPS, plenty of stuff in the kernel DOESN'T check for null. And this is a *style* document, not a calling conventions document (unless we're documenting the use of kmalloc/kfree as well as layout?
If we're doing that, we may well want to expand it slightly to cover the case of 2 kmallocs, a 'goto out1' and 'goto out2' to demonstrate proper unwinding/freeing....
PATCH, RFC: Version 3 of 2.6 Codingstyle
In reply to Michael FrankChanges:
Add reference to scripts/Lindent
Cleanups, spelling fixes and numbering of chapters.
Regards
Michael
Patch against Version 2. Patch against in-kernel version attached
CodingStyle renamed from CodingStyle.mhf.orig.2 +36 -35
@@ -42,7 +42,7 @@ do_something_everytime; Outside of comments and except in Kconfig, spaces are never used for -indentation. +indentation, and the above example is deliberately broken. Don't leave whitespace at the end of lines.
@@ -52,10 +52,12 @@ Coding style is all about readability and maintainability using commonly available tools. +The limit on the length of lines is 80 columns and this is a hard limit. + Statements longer than 80 columns will be broken into sensible chunks. -Descendant's are always shorter than the parent and are placed substantially -to the right. The same applies to function headers with a long argument list. -Long strings are as well broken into smaller strings. +Descendants are always substantially shorter than the parent and are placed +substantially to the right. The same applies to function headers with a long +argument list. Long strings are as well broken into smaller strings. void fun(int a, int b, int c) {
@@ -67,8 +69,7 @@ next_statement; } - - Chapter : Placing Braces + Chapter 3: Placing Braces The other issue that always comes up in C styling is the placement of braces. Unlike the indent size, there are few technical reasons to
@@ -121,7 +122,7 @@ comments on. - Chapter : Naming + Chapter 4: Naming C is a Spartan language, and so should your naming be. Unlike Modula-2 and Pascal programmers, C programmers do not use cute names like
@@ -154,10 +155,10 @@ See next chapter. - Chapter : Functions + Chapter 5: Functions Functions should be short and sweet, and do just one thing. They should -fit on one or two screens full of text (the ISO/ANSI screen size is 80x24, +fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24, as we all know), and do one thing and do that well. The maximum length of a function is inversely proportional to the
@@ -181,10 +182,10 @@ and it gets confused. You know you're brilliant, but maybe you'd like to understand what you did 2 weeks from now. -Centralized exiting of functions + Chapter 6: Centralized exiting of functions -Albeit deprecated by some people, the goto statement is used frequently -by compilers in form of the unconditional jump instruction. +Albeit deprecated by some people, the equivalent of the goto statement is +used frequently by compilers in form of the unconditional jump instruction. The goto statement comes in handy when a function exits from multiple locations and some common work such as cleanup has to be done.
@@ -193,16 +194,17 @@ - unconditional statements are easier to understand and follow - nesting is reduced -- errors by not updating individual exit points when making modifications - are prevented +- errors by not updating individual exit points when making + modifications are prevented - saves the compiler work to optimize redundant code away ;) int fun(int ) { int result = 0; char *buffer = kmalloc(SIZE); + lock(something); - if (buffer == 0) { + if (buffer == NULL) { result = -1; goto out; }
@@ -216,12 +218,13 @@ } ... out: - if (buffer) - kfree(buffer); + unlock(something); + if (buffer != NULL) // This test is not needed for kfree + kfree(buffer); // as kfree checks pointer return result; } - Chapter : Commenting + Chapter 7: Commenting Comments are good, but there is also a danger of over-commenting. NEVER try to explain HOW your code works in a comment: it's much better to
@@ -238,7 +241,7 @@ it. - Chapter : You've made a mess of it + Chapter 8: You've made a mess of it That's OK, we all do. You've probably been told by your long-time Unix user helper that "GNU emacs" automatically formats the C sources for
@@ -263,7 +266,7 @@ to add (setq auto-mode-alist (cons '("/usr/src/linux.*/.*\\.[ch]$" . linux-c-mode) - auto-mode-alist)) +auto-mode-alist)) to your .emacs file if you want to have linux-c-mode switched on automagically when you edit source files under /usr/src/linux.
@@ -276,14 +279,15 @@ However, that's not too bad, because even the makers of GNU indent recognize the authority of K&R (the GNU people aren't evil, they are just severely misguided in this matter), so you just give indent the -options "-kr -i8" (stands for "K&R, 8 character indents"). +options "-kr -i8" (stands for "K&R, 8 character indents"), or use +"scripts/Lindent", which indents in the latest style. "indent" has a lot of options, and especially when it comes to comment -re-formatting you may want to take a look at the manual page. But +re-formatting you may want to take a look at the man page. But remember: "indent" is not a fix for bad programming. - Chapter : Configuration-files + Chapter 9: Configuration-files For configuration options (arch/xxx/Kconfig, and all the Kconfig files), somewhat different indentation is used.
@@ -308,7 +312,7 @@ experimental options should be denoted (EXPERIMENTAL). - Chapter : Data structures + Chapter 10: Data structures Data structures that have visibility outside the single-threaded environment they are created and destroyed in should always have
@@ -339,9 +343,9 @@ have a reference count on it, you almost certainly have a bug. - Chapter : Inlines, Enums and Macros + Chapter 11: Macros, Enums and Inline functions -Macros defining constants and values in enums are capitalized. +Names of macros defining constants and labels in enums are capitalized. #define CONSTANT 0x12345
@@ -358,10 +362,9 @@ do { \ if (a == 5) \ do_this(b,c); \ - \ } while (0) -Things to avoid when doing macros: +Things to avoid when using macros: 1) macros that affect control flow:
@@ -374,7 +377,7 @@ is a _very_ bad idea. It looks like a function call but exits the "calling" function; don't break the internal parsers of those who will read the code. -2) macros that depend on having a local variable with magic name: +2) macros that depend on having a local variable with a magic name: #define FOO(val) bar(index, val)
@@ -382,16 +385,16 @@ code and it's prone to breakage from seemingly innocent changes. 3) macros with arguments that are used as l-values: FOO(x) = y; will -bite you if somebody e.g. turns FOO into inlined function. +bite you if somebody e.g. turns FOO into an inline function. -4) forgetting about sideeffects. Macros defining expressions must enclose the -expression in parenthesis. Note that this does not eliminate all side effects. +4) forgetting about side effects: macros defining expressions must enclose each +parameter and the expression in parentheses. #define CONSTEXP (CONSTANT | 3) #define MACWEXP(a,b) ((a) + (b)) - Chapter : Printing kernel messages + Chapter 12: Printing kernel messages Kernel developers like to be seen as literate. Do mind the spelling of kernel messages to make a good impression. Do not use crippled
@@ -400,5 +403,3 @@ Kernel messages do not have to be terminated with a period. Printing numbers in parenthesis (%d) adds no value and should be avoided. - -
CodingStyle renamed from CodingStyle.mhf.orig +196 -57
409 lines not on this page · raw message
Re: PATCH, RFC: Version 3 of 2.6 Codingstyle
CodingStyle line 394
Quoted 9 lines · Michael Frank
-4) forgetting about sideeffects. Macros defining expressions must enclose the
CodingStyle renamed from CodingStyle.mhf.orig.2 +2
-1-expression in parenthesis. Note that this does not eliminate all side effects. +4) forgetting about side effects: macros defining expressions must enclose each +parameter and the expression in parentheses. #define CONSTEXP (CONSTANT | 3) #define MACWEXP(a,b) ((a) + (b))
The statements above are incorrect.
Parentheses will never eliminate a side effect, macros do not have a "side effect problem". Functions and macros both can have side effects and sometimes side effect is a desired outcome.
Parentheses will only prevent surprises when argument expansion takes place:
#define times_2(a) (a * 2)
b = macro(a + 2);
will be expanded to:
b = (a + 2 * 2);
which is obviously not what programmer had in mind.
Signature · 1 line
Dmitry
PATCH, RFC: Version 4 of 2.6 Codingstyle
In reply to Michael FrankChanges:
Dropped confusing macro example for side efects and focus on precedence.
Added references.
diff against in-kernel version attached.
Regards
Michael
CodingStyle renamed from CodingStyle.mhf.orig.3 +19 -3
@@ -182,6 +182,7 @@ and it gets confused. You know you're brilliant, but maybe you'd like to understand what you did 2 weeks from now. + Chapter 6: Centralized exiting of functions Albeit deprecated by some people, the equivalent of the goto statement is
@@ -387,11 +388,12 @@ 3) macros with arguments that are used as l-values: FOO(x) = y; will bite you if somebody e.g. turns FOO into an inline function. -4) forgetting about side effects: macros defining expressions must enclose each -parameter and the expression in parentheses. +4) forgetting about precedence: macros defining constants using expressions +must enclose the expression in parentheses. Beware of similar issues in +macros using parameters. +#define CONSTANT 0x4000 #define CONSTEXP (CONSTANT | 3) -#define MACWEXP(a,b) ((a) + (b)) Chapter 12: Printing kernel messages
@@ -403,3 +405,17 @@ Kernel messages do not have to be terminated with a period. Printing numbers in parenthesis (%d) adds no value and should be avoided. + + + Chapter 13: References + +The C Programming Language, Second Edition +by Brian W. Kernighan and Dennis M. Ritchie. +Prentice Hall, Inc., 1988. +ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback). + +GNU manuals for cpp, gcc and indent, available from www.gnu.org, while in +compliance with K&R and this text. + +-- +This document was updated by a community effort on LKML on 14 February 2004.
CodingStyle renamed from CodingStyle.mhf.orig +212 -57
425 lines not on this page · raw message
Re: PATCH, RFC: Version 4 of 2.6 Codingstyle
CodingStyle line 418
Quoted 9 lines · Michael Frank
CodingStyle renamed from CodingStyle.mhf.orig.3 +9
-0+ Chapter 13: References + +The C Programming Language, Second Edition +by Brian W. Kernighan and Dennis M. Ritchie. +Prentice Hall, Inc., 1988. +ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback). + +GNU manuals for cpp, gcc and indent, available from www.gnu.org, while in +compliance with K&R and this text.
The Practice of Programming
Brian W. Kernighan, Rob Pike
Addison-Wesley, 1999, ISBN 0-201-61586-X
Re: PATCH, RFC: Version 3 of 2.6 Codingstyle
In reply to Dmitry TorokhovQuoted 11 lines · Dmitry Torokhov
CodingStyle line 394
Quoted 7 lines · Michael Frank
CodingStyle renamed from CodingStyle.mhf.orig.2 +2
-1-expression in parenthesis. Note that this does not eliminate all side effects. +4) forgetting about side effects: macros defining expressions must enclose each +parameter and the expression in parentheses. #define CONSTEXP (CONSTANT | 3) #define MACWEXP(a,b) ((a) + (b))The statements above are incorrect.
Quoted 3 lines
Parentheses will never eliminate a side effect, macros do not have a "side effect problem". Functions and macros both can have side effects and sometimes side effect is a desired outcome.
Macros do have a side effect problem, but it is not something which is fixed by parentheses. The problem comes when the argument of the macro is repeated more than once, or zero times, in the macro body. Then any side effect that the caller was expecting takes place the wrong number of times.
A subtler version occurs when the caller expects the side effect in an argument to occur before the action of the macro, but the macro doesn't expand the argument in that order.
See "Duplication of Side Effects" in the GNU CPP manual.
-- Jamie
PATCH, RFC: Version 5 of 2.6 Codingstyle
In reply to Michael FrankChanges:
Expanded references.
Pointer to RTL reference.
Cleanups and fixed more typos
diff against in-kernel version attached.
Regards
Michael
CodingStyle renamed from CodingStyle.mhf.orig.4 +27 -25
@@ -41,10 +41,10 @@ if (condition) do_this; do_something_everytime; -Outside of comments and except in Kconfig, spaces are never used for -indentation, and the above example is deliberately broken. +Outside of comments, documentation and except in Kconfig, spaces are never +used for indentation, and the above example is deliberately broken. -Don't leave whitespace at the end of lines. +Get a decent editor and don't leave whitespace at the end of lines. Chapter 2: Breaking long lines and strings
@@ -57,7 +57,7 @@ Statements longer than 80 columns will be broken into sensible chunks. Descendants are always substantially shorter than the parent and are placed substantially to the right. The same applies to function headers with a long -argument list. Long strings are as well broken into smaller strings. +argument list. Long strings are as well broken into shorter strings. void fun(int a, int b, int c) {
@@ -203,12 +203,9 @@ { int result = 0; char *buffer = kmalloc(SIZE); - lock(something); - if (buffer == NULL) { - result = -1; - goto out; - } + if (buffer == NULL) + return -ENOMEM; if (condition1) { while (loop1) {
@@ -219,9 +216,7 @@ } ... out: - unlock(something); - if (buffer != NULL) // This test is not needed for kfree - kfree(buffer); // as kfree checks pointer + kfree(buffer); return result; }
@@ -235,7 +230,7 @@ Generally, you want your comments to tell WHAT your code does, not HOW. Also, try to avoid putting comments inside a function body: if the function is so complex that you need to separately comment parts of it, -you should probably go back to chapter 4 for a while. You can make +you should probably go back to chapter 5 for a while. You can make small comments to note or warn about something particularly clever (or ugly), but try to avoid excess. Instead, put the comments at the head of the function, telling people what it does, and possibly WHY it does
@@ -344,7 +339,7 @@ have a reference count on it, you almost certainly have a bug. - Chapter 11: Macros, Enums and Inline functions + Chapter 11: Macros, Enums, Inline functions and RTL Names of macros defining constants and labels in enums are capitalized.
@@ -357,13 +352,13 @@ Generally, inline functions are preferable to macros resembling functions. -Macros with multiple statements should be enclosed in a do - while block. +Macros with multiple statements should be enclosed in a do - while block: -#define macrofun(a,b,c) \ -do { \ - if (a == 5) \ - do_this(b,c); \ -} while (0) +#define macrofun(a,b,c) \ + do { \ + if (a == 5) \ + do_this(b,c); \ + } while (0) Things to avoid when using macros:
@@ -389,12 +384,15 @@ bite you if somebody e.g. turns FOO into an inline function. 4) forgetting about precedence: macros defining constants using expressions -must enclose the expression in parentheses. Beware of similar issues in +must enclose the expression in parentheses. Beware of similar issues with macros using parameters. #define CONSTANT 0x4000 #define CONSTEXP (CONSTANT | 3) +The cpp manual deals with macros exhaustively. The gcc internals manual also +covers RTL which is used frequently with assembly language in the kernel. + Chapter 12: Printing kernel messages
@@ -404,7 +402,7 @@ Kernel messages do not have to be terminated with a period. -Printing numbers in parenthesis (%d) adds no value and should be avoided. +Printing numbers in parentheses (%d) adds no value and should be avoided. Chapter 13: References
@@ -414,8 +412,12 @@ Prentice Hall, Inc., 1988. ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback). -GNU manuals for cpp, gcc and indent, available from www.gnu.org, while in -compliance with K&R and this text. +The Practice of Programming +Brian W. Kernighan, Rob Pike +Addison-Wesley, 1999, ISBN 0-201-61586-X + +GNU manuals - where in compliance with K&R and this text - for cpp, gcc, +gcc internals and indent, all available from www.gnu.org. -- -This document was updated by a community effort on LKML on 14 February 2004. +Last updated on 16 February 2004 by a community effort on LKML.
CodingStyle renamed from CodingStyle.mhf.orig +215 -58
428 lines not on this page · raw message
Re: PATCH, RFC: Version 2 of 2.6 Codingstyle
In reply to Andries BrouwerQuoted 6 lines · Andries Brouwer
On Fri, Feb 13, 2004 at 04:49:30PM +0800, Michael Frank wrote:
CodingStyle renamed from CodingStyle.mhf.orig +1
-1-fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24, +fit on one or two screens full of text (the ISO/ANSI screen size is 80x24,Not an improvement.
IMHO it is.
Quoted 2 lines · Michael Frank
96 is not excessive and will reduce linecount and often makes things more readable.
96 is excessive.
Code that wraps is _really_ unreadable.
-Miles
Signature · 2 lines
Come now, if we were really planning to harm you, would we be waiting here, beside the path, in the very darkest part of the forest?