As far as I’m concerned, there’s only one way to write C-like code. First of all, you must select sane whitespace defaults in your editor. Here’s the one true way to configure Emacs.
(setq default-tab-width 8) (defun one-true-style () (c-set-style "bsd") (setq tab-width 8) (setq c-basic-offset 4) (setq indent-tabs-mode t)) (add-hook 'c-mode-hook 'one-true-style) (add-hook 'objc-mode-hook 'one-true-style) (add-hook 'c++-mode-hook 'one-true-style) (add-hook 'php-mode-hook 'one-true-style)
Other rules of thumb, most of which I picked up from Adobe:
- always use curly braces for if/else/for/while, even if you don’t need them
- every brace goes on a line by itself
- the * is adjacent to the variable name, not the typename
- no extra whitespace inside parens
- always use one space after comma to separate function args
- prefer &foo[i] over foo + i
- prefer foo == NULL over !foo
Here’s a concrete example:
#include <stdio.h> #include <unistd.h> #include <errno.h> int quux(char *foo, size_t len, const char *bar, int flags) { int i, j; char buf[BUFSIZ], *cp; if (foo == NULL) { errno = EFAULT; return -1; } for (i = 0; i < len; i++) { for (j = 0; j < BUFSIZ; j++) { /* something here */ } } return 0; }
I’ve never been a big fan of Hungarian notation for variable prefixes. I do think prefixes have a place; within a library all function names need to be prefixed with some short (3-6 char) name so it’s easy to see which APIs you’re using. I don’t see the point of decorating my variable names like pchFoo. Maybe because it’s too distracting to be constantly thinking of the Pacific Coast Highway.