Programming notes: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
m (→Notes on C) |
||
Line 17: | Line 17: | ||
<li>Don't put multiple commands on a single line. One command per line.</li> |
<li>Don't put multiple commands on a single line. One command per line.</li> |
||
<li>I dislike this layout because of its lack of symmetry |
<li>I dislike this layout because of its lack of symmetry |
||
<pre> |
<pre> |
||
if (i==2){ |
if (i==2) { |
||
i++; |
i++; |
||
} |
} |
||
</pre> |
</pre> |
||
and think this is cleaner |
|||
Much cleaner is this: |
|||
<pre> |
<pre> |
||
if (i==2) |
if (i==2) |
||
Line 30: | Line 30: | ||
} |
} |
||
</pre> |
</pre> |
||
However, I've now [http://en.wikipedia.org/wiki/Indent_style#Styles learned] that this is a matter of strong debate, and I definitely defer to [http://en.wikipedia.org/wiki/Indent_style#K.26R_style Kernighan & Ritchie] on this (but strongely side with [http://en.wikipedia.org/wiki/Indent_style#Variant:_Stroustrup Stroustrup] on the "else" statement). So, given this situation, choose either of these styles, but be consistent. |
|||
</li> |
</li> |
||
Latest revision as of 14:21, 7 April 2015
This is a collection of miscellaneous thoughts on coding style recommended for use in our lab.
Editor
- In general, use Emacs. GNU Emacs for OS X can be downloaded here.
- In a pinch, use vi. On our Linux systems as well as on OS X, this is actually vim, which offers syntax highlighting. (Note: on OS X, syntax highlighting seems to be disabled by default. Enable it by adding "syntax on" to your ~/.vimrc file.)
Notes on C
- Don't put multiple commands on a single line. One command per line.
- I dislike this layout because of its lack of symmetry
if (i==2) { i++; }
and think this is cleaner
if (i==2) { i++; }
However, I've now learned that this is a matter of strong debate, and I definitely defer to Kernighan & Ritchie on this (but strongely side with Stroustrup on the "else" statement). So, given this situation, choose either of these styles, but be consistent.
- For clarity, I prefer indentations to be 8 spaces (not 4). If you follow this, you'll be in good company. Insert the following snippet in your ~/.emacs file:
(defconst my-c-style '((c-basic-offset . 8) (c-offsets-alist . ((substatement-open . 0) ) ) ) "C Style") (defun my-c-mode-common-hook () (c-add-style "personal" my-c-style t) (setq fill-column 135) ) (add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
-
The following is a surprisingly common programming mistake:
double x, y; if (x == y) { do_something(); }
You should not test for exact equality between two floating point numbers, since this comparison may fail due to rounding errors. Instead, do:
#define EPS 1e-9 /* or some other threshold small enough for your purposes */ double x, y; if (fabs(x-y) < EPS) { do_something(); }