embedded software boot camp

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: , , ,

3 Responses 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?

  2. [...] Coding Standard Rule #2: Use const Whenever Possible for more on the use of const by [...]

  3. Dan Szabo says:

    I always use a #define over const when I have a single peice of constant data, for example: when defining array lengths or maximum/minimum values for data. I’ve found that the compiler can often put the value directly into the assembly instruction for the projects I’ve worked on. I’m sure that this is going to be dependent on both the compiler and processor being used, but it’s in our coding standard to do it that way, so thats how I do it.

    I always use const when I have data that is tightly coupled, such data in a structure or array that is all constant. This is in addition to using const as a ‘do not overwrite this data’ declaration for read only hardware registers.

Leave a Reply