Home / Learn Embedded C / const-Correctness in Embedded C

const-Correctness in Embedded C

Using const to mark data that should never change, and to place lookup tables in flash.

The short versionUsing const to mark data that should never change, and to place lookup tables in flash.

Theory in plain words

What it is

const marks a variable (or pointer target) as read-only: the compiler rejects any code that tries to modify it, and the data can often be placed in flash instead of using precious RAM.

Why it matters

Lookup tables (like a sine wave table, or a list of valid command names) never change after the program is written — marking them const lets the compiler store them in flash, saving RAM.

Mechanically speaking

const int x; means x cannot be reassigned; const int *p means the data p points to cannot be changed through p (though p itself can point elsewhere, unless it is also declared as a const pointer).

Shows up in

  • Lookup tables
  • Flash-resident constant data
  • API safety (marking "read-only" parameters)

Try it

A const lookup tableC: edit and run

On a real chip, this const array can be placed directly in flash memory instead of copied into RAM at startup.

DeclarationMeaning
const int x;x cannot be reassigned
const int *p;the data p points to cannot be changed through p
int * const p;p itself cannot be made to point elsewhere

Try it: a read-only function parameter

A function parameter that promises not to modify its dataC: edit and run

const int *values documents (and the compiler enforces) that sum_readonly only reads the caller's array and never modifies it.

Check yourself

1. Why mark a lookup table as const in embedded C specifically?