Programming notes

From csml-wiki.northwestern.edu
Revision as of 14:21, 7 April 2015 by Administrator (talk | contribs) (→‎Notes on C)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

This is a collection of miscellaneous thoughts on coding style recommended for use in our lab.

Editor

  1. In general, use Emacs. GNU Emacs for OS X can be downloaded here.
  2. 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

  1. Don't put multiple commands on a single line. One command per line.
  2. 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.

  3. 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)
    
  4. 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();
    }