Saturday, December 06, 2025

Things which make C/C++ source code easier to understand

I end up reading a lot of C/C++ source code from various sources in my role as an embedded firmware engineer.  There are a few rules I try to follow to make my code easier for others to decipher.

  • Include explanations for any acronyms you use in function or variable names and even in comments.  Don't assume that everyone has the same background as you do.
  • Don't ever use magic numbers.  When I'm looking for all code which writes or reads a bit within a register, I don't want to have to try to grep for every hex value which includes that bit and even worse, sometimes people define register values as decimal which makes less sense to low level programmers like me.  Just define it with a mnemonic name and use the boolean or operator "|" to define the set of bitmasks required.  Think of the poor sod who gets stuck maintaining your code.
  • Start your functions with an open brace starting in column 1 after the function name/parameters.  End functions with a close brace in column 1 for the same reason.  It makes it easier to search for function names within a source file.  In an editor which uses a vi style user interface, the command "/^{" (without the quotes and followed by the Enter key will find the first instance.  Then "n" will find the next one and can be repeated as many times as desired.
  • Emulate whatever indentation style you found in the code if you inherited it from someone else.  It's irritating to have a mix of tab and space characters with no hint of what tab stops the author used.

No comments:

Post a Comment