6 ms·
Plan 9 Coding Conventions for C
- shin_lao 13y agoI appreciate that these are old rules, nevertheless, I have the following comments: don't use // comments; some old Plan 9 code does, but we're converting it as we touch it. We do sometimes use // to comment–out a few lines of code. Doesn't make sense with any decent editor, you ought to comment via macros. no braces around single–line blocks (e.g., if, for, and while bodies) I kind of like enforcing the opposite (always use braces). Otherwise you end up with things like: if (statement) one; two;
- gosu 13y agoOS code has to do a lot of validating input and braceful style causes functions to be visually dominated by boring validation code. It's also surprisingly nice to have a visual distinction between boring conditions like if(!found) return; and the more interesting branches that require the braces. Not sure I follow you on the one; two; example. Why would you have two statements per line in the first place? (You do realize that the "two;" isn't in the if block, right?)
- shin_lao 13y agoBecause developer one wrote if (statement) one; And developper two added if (statement) one; two; too quickly
- jomar 13y agoThe actual problem there is that developer two checked something in without thinking about it, reading it, or examining the diffs of the change. If you had a coding convention of always using braces in if statements, you might be insulated from this particular symptom or instance of the problem, but you still have the underlying problem that people are doing things without thinking.
- qznc 13y ago"you still have the underlying problem that people are doing things without thinking" You can solve this problem?
- zimpenfish 13y agoWhy not take advantage of every safety net you can? People are fallible, mistakes get made.
- loup-vaillant 13y agoBecause if you do, the safety net will collapse your circus tent by their sheer weight. The actual argument has been made in sibling comments: braces are verbose, and the mistake we speak of is exceedingly rare in practice. For simple one-liners, the verbosity costs more than the lack of safety net.
- mercurial 13y agoSure, but how often does this happen in practice? I have worked with 'no convention'/'multiple conventions'/'mostly no braces for single statements' and have never seen this particular mistake. I can see how it would be difficult to track down, on the other hand, braces for single comments add to line noise.
- barrkel 13y agoI've worked on multi-million line projects and have also never seen this mistake made. So in my experience, it is so vanishingly rare that the costs in visual gunk and decreased code density are not worth it. A lint tool checking for suspicious indentation would be a better use of labour.
- k3n 13y agoI've encountered it just enough times to avoid it 100%. I think in my scenario, the problems have been compounded by an overall lax (lazy) coding style on the part of my predecessors, in that many of them were junior devs who virtually made-up their own coding styles. These devs treated whitespace like it cost money, and avoided any unrequired use of spaces, tabs, and newlines. These types of conventions -- no curlies around simple blocks -- aren't too bad if a) your devs are adequately seasoned, and b) your devs believe in whitespace. For instance, this isn't really so bad: if (foo) foo(); else bar(); Hell, that's clean! But it's stuff like this that causes issues: if(foo)foo(); else bar(); Sometimes I'm lucky and find this: if (foo) foo(); else { bar(); baz(); } The best is abominations like this though; first, the sane formatting: if (foo) while (i++ < x) foo(i); else bar(); Or, as I have found it: if(foo)while(i++<x)foo(i); else bar(); Seriously, that's enough for me to revoke commit privs.
- to3m 13y agoI've seen it once, in 13 years of working professionally in C. I think two people changed the same one-line if statement, but for two different reasons (probably adding two different new features to the same bit of code). And after an automatic merge it became something like this: if(flag) set_other_flag=1; call_function(); (both lines necessary) Anyway, it didn't take long to narrow it down to that bit of code but it took a few more minutes to figure out why the function was always getting called. I couldn't work out what was going on until I looked at the disassembly and was forced to reassess my opinion of what code was actually being compiled. Too much python in my diet, perhaps. I remember being surprised at the time that it had taken so long for this to happen, and I made a mental note to keep an eye out for more occurrences. That was summer 2006, and I haven't seen it happen since.
- mosburger 13y agostuff like this can happen if you're not careful w/ preprocessor macros too. #define one a;b; if (statement) one;
- gosu 13y agoI think that such a developer would be equally as likely to forget to free() memory or overflow a buffer. I assume that the reasoning is that people who don't know C well enough or are too forgetful shouldn't be working on the Plan9 codebase anyway, so why optimize for such a bad case when there are definite costs to doing so (as I mentioned before)?
- ibotty 13y agobut two statements in one line is not exactly encouraged by the rules either.
- snov 13y agomy favorite is if (statement) // one; two;
- jacobparker 13y agoAnd don't forget: if(a) if(b) x; else y; This doesn't do what the indentation implies. (http://en.wikipedia.org/wiki/Dangling_else http://en.wikipedia.org/wiki/Dangling_else) Walter Bright (creator of D, etc.) has an article where he discusses his interesting choice to make that grammar form illegal in D. He mentions that after doing this he found a bug in D's runtime library. http://www.drdobbs.com/cpp/dangling-else-yet-again/231602010 http://www.drdobbs.com/cpp/dangling-else-yet-again/231602010
- angersock 13y agoJust see that made me foam at the mouth a little...grr. We generally don't even like have non-curlied one-liners in our conditionals.
- mercurial 13y agoThis makes a good point for Python syntax, where you can't by construction end up in situations like that.
- jacobparker 13y agoNote that any static analyzer that is worth something will warn about this in C/C++. For example, clang will warn with the option -Wdangling-else (implied by -Wall)
- maw 13y agoTrue, but the flip side is that in Python automatic indentation cannot possibly work.
- safod 13y agoWhy not? vim indents one more when encountering a colon at the end of a line. It also de-indents when encountering a return or break statement. Of course in all other cases you have to de-indent manually, however, hitting backspace once is not more work than typing a closing curly brace.
- nteon 13y agoI can't stand macro comments - it makes it impossible to figure out whats going on without being sure to open the file in a specific editor with a specific project loaded. Say you have a separate lib project used by an application - if you open up an individual file from that lib while working on the application in Visual Studio it won't have the necessary context to 'comment out' macro comments. Its also hostile to people who use vi and emacs.
- papsosouid 13y ago>I appreciate that these are old rules They are current rules also. The rules are largely the same as BSD rules, and go rules. Just because they are old, doesn't mean the people who wrote them moved on to doing what the trendy javascript kids do.
- mheathr 13y agoI always use braces in order to protect my future self from my current self. I don't want to end up introducing a logic error in the program because I overlooked proper scope while less coherent later on.
- peteretep 13y agoeg: http://plan9.bell-labs.com/sources/plan9/sys/src/cmd/ramfs.c http://plan9.bell-labs.com/sources/plan9/sys/src/cmd/ramfs.c
- jstanley 13y agoAnybody know what the: int needfid[] = { [Tversion] 0, [Tflush] 0, [Tauth] 0, syntax means? Is this some Plan 9 extension, or is it just something I've never encountered? EDIT: I guess the value in the []'s is the array index to set the value of.
- _pmf_ 13y ago> Is this some Plan 9 extension, or is it just something I've never encountered? It's C99 (I also only saw it in C99 articles, never in production code). See http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits...
- pdw 13y agoIt's heavily used in the Linux kernel and in the Linux world in general. But Visual Studio doesn't support it, so projects that target Windows pretty much have to avoid it.
- pdw 13y agoA variation of this syntax was standardized in C99: int needfid[] = { [Tversion] = 0, [Tflush] = 0, It works for structs too: struct blah needfid = { .version = 0, .flush = 0,
- glurgh 13y agoThat's right, it's a designated initializer, except the standard c99 way requires an =. gcc didn't/doesn't but that's nonstandard. So it is an extension, just not a plan9 one - a gcc-ism. clang's error/warning, as usual, is very helpful so it's worth it just to try clang when running into weirdness like that: warning: use of GNU 'missing =' extension in designator [-Wgnu-designator]
- deleted 13y ago[deleted]
- fijal 13y ago* variable and function names are all lowercase, with no underscores. That sounds odd
- dietrichepp 13y agoNot really. Look at everything in the C standard library: fopen(), strcmp(), malloc(), etc.
- rat87 13y agoyes and c stdlib style naming is mainly considered legacy these days and multi word "variable and function [in] all lowercase, with no underscores" is frowned upon.
- emillon 13y agoIn the standard there is a notion of "significant prefix length". ie, your symbol names may actually be truncated. In C89 the minimum guaranteed length for exported symbols was 6 (IIRC) which explains why the libc symbols are so terse. Adding underscores would greatly reduce the number of significant characters (of course, all of this is mostly obsolete these days).
- davidw 13y agoI am kind of partial to Tcl's C code: https://github.com/tcltk/tcl/blob/master/generic/tclConfig.c https://github.com/tcltk/tcl/blob/master/generic/tclConfig.c Although I think arguing for less uppercase/camelcase would not be entirely out of place. Still though, it's very nice to read.
- shared4you 13y ago> no white space after the keywords if, for, while, etc. Woh, my workplace enforces the exact opposite! The idea is that if, while, etc are not functions, therefore `if (x)` is unacceptable but `my_func(x)` is ok. I personally prefer `if(x)` though.
- oddthink 13y agoI think most places enforce the opposite. There's a strain of very-little-space style out there, but I'm not sure where it comes from. Maybe Pike, for all I know: http://www.literateprogramming.com/pikestyle.pdf http://www.literateprogramming.com/pikestyle.pdf is certainly rife with it.
- qznc 13y agoThere is no right or wrong here. The important thing is consistency across a project.
- maw 13y agoSpaces before parens doesn't matter too much, but with respect to spaces before commas all relativism goes straight out the window: putting a space before a comma is objectively better practice.
- cypher543 13y ago[...] don't try to write the most compact code possible but rather the most readable. Don't conventions 6, 7, 8, and 11 violate this?
- angersock 13y agoProbably my favorite take-away from this: "Ultimately, the goal is to write code that fits in with the other code around it and the system as a whole. If the file you are editing already deviates from these guidelines, do what it does. After you edit a file, a reader should not be able to tell just from coding style which parts you worked on." This is a real boon to other people on your team.
- comatose_kid 13y agoMost good professionals I have worked with adhere to this simple rule.
- marios 13y agoThe efficiency and comments part read like a tl;dr version of Kernighan & Pike The Practice of Programming[1], which, I might add, is an excellent read. As for coding conventions, I quite like OpenBSD's (man style)[2], which are also present on FreeBSD. Though I rarely write C these days, I have to read some every now and then, and code from BSD projects following those conventions feels very readable. [1] http://www.amazon.com/Practice-Programming-Addison-Wesley-Professional-Computing/dp/020161586X http://www.amazon.com/Practice-Programming-Addison-Wesley-Pr... [2] http://www.openbsd.org/cgi-bin/man.cgi?query=style&sektion=9 http://www.openbsd.org/cgi-bin/man.cgi?query=style&sekti...
- doki_pen 13y agoIt's funny that many modern style rules are the exact opposite of these ones.
- zxcdw 13y agoWhich ones, in which languages and in what kind of projects?
- papsosouid 13y agoIt isn't a question of "modern" or "old". GNU has always had absurdly terrible styles rules for example. It isn't a "modern" thing at all.
- kstenerud 13y agoOdd that they don't like gotos. That's going to make cleanup code pretty ugly.
- realrocker 13y agoGo plug: I first read about these conventions in a Go article[1]. [1]http://talks.golang.org/2012/splash.article#TOC_5 http://talks.golang.org/2012/splash.article#TOC_5.
- gioele 13y ago> * no tabs expanded to spaces. Oh, finally. Tabs for indentation levels, spaces for alignment. How hard can it be?
- nnq 13y agohard. someone even made a comic to explain how hard: http://www.emacswiki.org/SmartTabs http://www.emacswiki.org/SmartTabs
- papsosouid 13y agoThat comic doesn't explain anything. That post also doesn't explain how hard it is.
- JulianMorrison 13y agoSomeone needs to write "c fmt"