[chbot] C Coding Style

Peter Harris petes.username at gmail.com
Thu Sep 22 22:01:09 BST 2016


Hi Richard
I agree with Volker and Charles that readability is the single most
important thing.
The fact is that we spend more time reading code than writing it so it is
worth taking the time to make it as readable as possible.

<styleOpinion>
To that end there are 2 changes I would make to this example namely to
dispose of single letter variable names and magic numbers so:
// ----------
if (something == 45)
  {
    for (i = ...)
    {
      a += 5;
    }
  }
  else
  {
    do something else;
  }
// ----------
becomes:

// ----------
#define INTERESTING_THRESHOLD 45
#define STEP_SIZE                            5

  if (something == INTERESTING_THRESHOLD)
  {
    for (increment_number = 0;  increment_number <
required_number_of_increments; increment_number ++)
    {
      useful_variable_name += STEP_SIZE;
    }
  }
  else
  {
    do something else;
  }
// ----------
</styleOpinion>

<codingTip>
When cutting, pasting & editing code the following can and does happen:
  if (something == INTERESTING_THRESHOLD)
becomes
  if (something_else >= TEST_THRESHOLD)
 becomes
  if (final_agreed_on_variable_name = FinalThreshold_CONSTANT)

I'm sure you can all see the bug in the final line where the 'if' is
testing the result of the assignment '=' rather than the intended
comparison '==' which has been edited out. We now have a corrupted variable
value and the 'if' is always executed.
This is a typical Friday afternoon/Monday morning bug. It is true that many
compilers will spot this and give you an error or at least a warning but
not all of them do, I personally lost several days to an instance of this
bug and have adopted the following coding practice to prevent it from
happening again.

The answer is to simply put the constant value on the left so:
if(CONSTANT == variable) // works as expected but the bug
if(CONSTANT = variable)   // just won't compile.
Granted the code is not as easy to read especially when '>' or '<' are in
play but I find this to be a worthwhile compromise.
</codingTip>

IPersonallyFindCamelCapsToBeAnApallingAffrontToComprehesibility
and_find_the_lower_case_underscore_format_to_be_more_legible

  Peter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.ourshack.com/pipermail/chchrobotics/attachments/20160923/3919da5e/attachment.html>


More information about the Chchrobotics mailing list