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.  Just define it with a mnemonic name and use the "or" function to define a 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.
  • 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: