Embedded C Basics – const

We will try to understand the use of const from the perspective of an embedded systems developer and try to evaluate a few common queries which arise in its use.

So what is a the const qualifier? A software developer will quickly answer that it is a keyword used to declare a variable in the program whose value cannot be changed.

const uint32_t value = 0xDEADBEEF;

This response begs the question, why do we need a variable to hold a constant value? We can very well use a MACRO.

#define VALUE 0xDEADBEEFu;

Lets understand it with an practical example in a microcontroller. A microcontroller will have different kinds of memories, but for the simplicity let us consider the DATA memory (RAM) and CODE memory (ROM/FLASH). Below is a snapshot of the memory map of the MCU used in the example.

Memory_Map

For this example we just need to understand that CODE memory lies between address 0x00000000 and 0x1FFFFFFF. DATA memory begins from address 0x20000000.

The code written is very simple. It has a variable value and a pointer variable ptr_value which holds the address of value.

So lets see what happens when we declare a global variable.normal_global_variable

We can see that, value is stored in the RAM area.Now lets see what happens when we declare value to be const.const_global_variable

So, whenever a variable is declared const, it is made to reside in the CODE memory as opposed to the DATA memory for general variables.

A programmer can update any variable in the RAM (DATA memory) by simply executing

value = new_value;

However the same is not possible to update the FLASH (CODE memory) with a simple line of code.

It is at this point we come to light that const provides the programmers a way to define a variable, which is read-only memory, not read-write memory.

A practical use case for use of const is to define the hardware registers which should have read only permissions.

Leave a comment