| Multiply, divide and
modulus come before add and subtract; use parenthesis for everything else |
In C expressions, you can assume that multiply (*),
divide (/) and modulus (%) come before add (+) and subtract (-). Parenthesis should be
used around everything else. C does a very good job of defining operator precedence,
however most programmers don't remember the exact order. Using parenthesis removes this
uncertainty. |
| Put constants on the
left when comparing for equality |
One common mistake is accidentally assigning a value to
a variable when what was intended was comparing for equality.
if ( variable = CONST_VAL ) /* accidental assignment */
|
By putting the constant on the left of the equality operator the compiler would have
identified this as an error.
if ( CONST_VAL = variable ) /* compiler error */
|
if ( CONST_VAL == variable )
|
Functions in equality comparisons should use a similar technique.
if ( function() == variable )
|
|
| Use mathematical
notational order when checking for ranges |
When a variable is to be tested to see if it is within
or outside of a specified numeric range, organize the logical expression such that it
reads as a mathematical expression. For example, if a variable ("a") must be
within the range of LOW through HIGH inclusive a common representation would be:
if ( a >= LOW && a <= HIGH ) /* POOR */
|
Instead we should describe that as (LOW <= a <= HIGH) in
mathematical notation. Thus the if-statement might look like:
if ( LOW <= a && a <= HIGH ) /* BETTER */
|
Correspondingly, if the variable should be outside of the numeric range it could be
expressed as:
if ( a < LOW || HIGH < a )
|
|
| Place smaller value on left
in binary comparison |
When two values are compared place the smaller value on
the left of the binary less-than operator ("<").
if ( HIGH > LOW ) /* POOR */
|
By placing the smaller value on the left this makes the expression resemble the
standard mathematical notation.
if ( LOW < HIGH ) /* BETTER */
|
|
| Code in a word-size
independent manner |
Word size affects masks. The following snippet code
clears the right most nibble of an int on some 68000 systems.
On some other machines it also clears the upper two bytes. You should use the following
instead:
|
| Be careful of sign extension
for shift right operations |
Some compilers will treat the right shift (>>)
operator as an arithmetic shift (causing the sign bit to be replicated) instead of a
logical shift on signed integers. If you must have logical shift make sure that you are
dealing with an unsigned data type. Also be aware that some compilers don't give you
access to an arithmetic shift (except through in-line assembly). A good rule is to only
use the logical form of shift. Arithmetic operations should be done with the standard
arithmetic operators. (short) 0x8000 >> 3 == 0xF000 // some compilers
will generate this
(unsigned short) 0x8000 >> 3 == 0x1000
|