Programming notes: Difference between revisions

From csml-wiki.northwestern.edu
Jump to navigation Jump to search
Line 2: Line 2:


<ol>
<ol>

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


=== Notes on C ===
=== Notes on C ===

<ol>


<li>For symmetry reasons, I dislike this layout:
<li>For symmetry reasons, I dislike this layout:
<pre>
<pre>
if (x==2){
if (i==2){
x++;
i++;
}
}
</pre>
</pre>
Far cleaner is this:
Far cleaner is this:
<pre>
<pre>
if (x==2)
if (i==2)
{
{
x++;
i++;
}
}
</pre>
</pre>
Line 34: Line 38:
)
)
(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
</pre>
</li>

<li>
The following is an amazingly common programming mistake:
<pre>
double x, y;
if (x == y)
{
do_something();
}
</pre>
Due to rounding errors, you should not test for exact equality between two floating point numbers (or a floating point number and a constant). Instead, do:
<pre>
#define EPS 1e-9 /* or some other threshold small enough for your purposes */
double x, y;
if (fabs(x-y) < EPS)
{
do_something();
}
</pre>
</pre>
</li>
</li>

Revision as of 14:50, 25 June 2014

This is a collection of recommendations on programming style.

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

    Notes on C

    1. For symmetry reasons, I dislike this layout:
      if (i==2){
              i++;
      }
      

      Far cleaner is this:

      if (i==2)
      {
              i++;
      }
      
    2. 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)
      
    3. The following is an amazingly common programming mistake:
      double x, y;
      if (x == y)
      {
              do_something();
      }
      

      Due to rounding errors, you should not test for exact equality between two floating point numbers (or a floating point number and a constant). 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();
      }