How to Use const to Save RAM in Embedded C
In embedded C, using
const tells the compiler to store variables in flash memory (program memory) instead of RAM, saving RAM space. This is especially useful for fixed data like strings or lookup tables that do not change during program execution.Syntax
The const keyword is placed before a variable declaration to indicate that its value will not change. This allows the compiler to place the variable in read-only memory (flash) instead of RAM.
Example parts:
const: keyword to mark data as constanttype: data type likeint,charname: variable name= value: optional initialization
c
const int fixedValue = 100; const char message[] = "Hello";
Example
This example shows how using const stores data in flash memory, saving RAM. The message string is constant and placed in flash, while counter uses RAM.
c
#include <stdio.h> const char message[] = "Embedded C"; // Stored in flash memory int counter = 0; // Stored in RAM int main() { printf("Message: %s\n", message); counter++; printf("Counter: %d\n", counter); return 0; }
Output
Message: Embedded C
Counter: 1
Common Pitfalls
Common mistakes include:
- Not using
constfor fixed data, wasting RAM. - Trying to modify
constdata, which causes compiler errors. - Forgetting to initialize
constvariables, which is required.
Example of wrong and right usage:
c
// Wrong: Modifying const data causes error const int value = 10; // value = 20; // Error: assignment of read-only variable // Right: Use non-const if modification needed int variable = 10; variable = 20;
Quick Reference
Tips to save RAM using const in embedded C:
- Use
constfor fixed strings and lookup tables. - Initialize
constvariables at declaration. - Do not modify
constdata after initialization. - Check your compiler/linker map to confirm data placement.
Key Takeaways
Use
const to store fixed data in flash memory, saving RAM.Always initialize
const variables when declaring them.Do not try to modify
const data; it is read-only.Use
const for strings and lookup tables to reduce RAM usage.Verify memory placement with your compiler or linker tools.