0
0
Power-electronicsConceptBeginner · 3 min read

What is const keyword in Embedded C: Explanation and Usage

In Embedded C, the const keyword is used to declare variables whose values cannot be changed after initialization. It tells the compiler to protect these variables from accidental modification, which is useful for fixed data like hardware addresses or configuration values.
⚙️

How It Works

Think of the const keyword as a 'do not change' sign for a variable. When you mark a variable as const, you tell the compiler that this value should stay the same throughout the program. This is like writing a rule on a sticky note that says "Don't erase or rewrite this." The compiler then enforces this rule by giving an error if the program tries to change the value.

In embedded systems, where hardware registers or fixed configuration values are common, using const helps prevent bugs caused by accidental changes. It also allows the compiler to optimize the code better, sometimes placing these values in read-only memory, saving precious RAM space.

💻

Example

This example shows how to declare a constant integer and what happens if you try to change it.

c
#include <stdio.h>

int main() {
    const int sensorThreshold = 100;
    printf("Sensor threshold is %d\n", sensorThreshold);
    // sensorThreshold = 120; // Uncommenting this line will cause a compile error
    return 0;
}
Output
Sensor threshold is 100
🎯

When to Use

Use const when you have values that should never change after being set. This includes:

  • Hardware addresses or registers that must remain fixed.
  • Configuration values that are set once and used throughout the program.
  • Lookup tables or fixed data arrays.

Using const helps avoid accidental bugs and can improve program safety and efficiency, especially in embedded systems where memory and reliability are critical.

Key Points

  • const makes variables read-only after initialization.
  • It helps prevent accidental changes to important values.
  • Allows compiler optimizations and better memory usage.
  • Commonly used for hardware addresses, fixed configs, and lookup data.

Key Takeaways

The const keyword protects variables from being changed after they are set.
Using const improves code safety and helps prevent bugs in embedded systems.
Const variables can be stored in read-only memory, saving RAM.
Apply const to fixed hardware addresses, configuration values, and constant data.
Trying to modify a const variable causes a compile-time error.