Const

  • The const keyword means that the variable you declare is read-only. In most introductory coding classes, const is taught meaning a variable’s value will not change. However, particularly in the embedded world, it is important to understand the distinction.

  • To further define, a read-only variable means your program can only read this variable, it cannot write or change it in any way, shape, or form. In embedded, however, the microcontroller itself can update variables, and the limitations of const do not apply to it, hence why the distinction is made between read-only and constant.

  • As an example, consider the code snippet below:

    • A bit of background, on most microcontrollers there is a register that you can read to get the state of an input pin (i.e. whether it is high or low). An example from an Atmega 328 datasheet is shown below:

    • //This variable points to the GPIO state register //More specifically, tells us if the input signal on a set of pins is either high or low volatile const* GPIO_STATE_REGISTER = PINB;
    • We notice that PINB can only be read, not written to, thus we should mark it in our code as const to prevent inadvertently modifying the register. However, the value can change, as this register reflects if a pin on a microcontroller is high or low, and the MCU itself will update the contents of the register when such a change occurs.

    • As discussed in the volatile keyword section, we also declare this to be volatile as its value can change unexpectedly as we do not know when the pin on the microcontroller will be toggled high or low.