Coding Standard Rule #2: Use const Wherever Possible

Tuesday, March 24th, 2009 by Michael Barr

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.

Coding Standard Rule #1
Coding Standard Rule #3

These rules are excerpts from the Embedded C Coding Standard book.

Tags: , , ,

One Response to “Coding Standard Rule #2: Use const Wherever Possible”

  1. Dan says:

    Absolutely. The biggest benefit of “const” is the added safety. It should be used as much as possible.Another benefit of “const”, especially for large structures, tables, etc… is tighter code.For example, declaring a table of bitmaps or fonts as “const” prevents the C-runtime startup code from copying the data into a writeable RAM copy.Less RAM usage, faster initialization and protection from writes/modification…. what’s not to like?

Leave a Reply