Home / Learn Embedded C / const and Placing Data in Flash

const and Placing Data in Flash

Using const to move read-only data out of precious RAM and into flash.

The short versionUsing const to move read-only data out of precious RAM and into flash.

Theory in plain words

What it is

Marking data const (and never writing to it) lets the compiler/linker place it in flash instead of copying it into RAM at startup, which matters enormously on RAM-starved chips.

Why it matters

A 1 KB lookup table or font bitmap costs almost nothing in flash (which is often large) but could be a meaningful fraction of total RAM (often much smaller) — const is the simplest RAM-saving tool available.

Mechanically speaking

Without const, the compiler must assume the data might be written to, so it typically copies an initialized global array into RAM at startup; with const, that copy (and the RAM it would use) is unnecessary.

Shows up in

  • Lookup tables
  • Font/image data
  • RAM budgeting

Try it

Comparing a const table against a non-const oneC: edit and run

Both print the same value here, but on a real chip only flash_table avoids using any RAM at all.

Tip:This is exactly why the "A const lookup table" example earlier in this course used const — on real hardware that array can live entirely in flash.

Try it: a const string table that never needs RAM

A fixed menu of messages stored once, read many timesC: edit and run

Because messages is const and never written to, a real compiler can place the whole table in flash and skip copying it into RAM at startup.

Check yourself

1. Why can const data often be stored only in flash, not copied into RAM?