Another in a continuing series of blog posts about simple rules for keeping bugs out of embedded software written in the C programming language.
Rule: The const keyword shall be used whenever possible, including:
- To declare variables that should not be changed after initialization,
- To define call-by-reference function parameters that should not be modified (e.g., char const * p_data),
- To define fields in structs and unions that cannot be modified (e.g., in a struct overlay for memory-mapped I/O peripheral registers), and
- As a strongly typed alternative to #define for numerical constants.
Reasoning: The upside of using const as much as possible is compiler-enforced protection from unintended writes to data that should be read-only.
These rules are excerpts from the Embedded C Coding Standard book.