C Programming Constant Variables

Last modified by Microchip on 2023/11/10 11:00

The term constant variables seems like a complete contradiction in terms but it is an accurate description. Earlier in this course, we discussed the concept of a variable, how it defines memory storage requirements, and how the value it contains should be handled by the compiler. All of that still applies here but with one significant difference: when the variable is defined, its type is modified by the const keyword:

const type identifier = value;

This has the effect of creating a variable, allocating memory for it, and initializing it with the value value as discussed earlier but the const keyword will prevent you from building any code that changes the value of the variable.

So, if we have the following declaration:

1    const float PI = 3.14159;

The linker would allocate 4 bytes of memory to store the IEEE-754-encoded value representing the number 3.14159. This can be a good thing in some cases, but in the embedded world, it is usually a poor use of resources when #define could do it without the overhead.

In recent years, many books on C have shown this method of constant creation as the only method, completely ignoring the #define method, which has been used since C's earliest days. While this is fine on a PC where memory is cheap, it is a very expensive proposition in the embedded world. Constant variables take up as much space as any other variable. If all you intend to do is remove magic numbers from your program to make it easier to read, this will result in a huge waste of memory (unless you have a clever linker and a good optimizer). However, if you are using these values in much the same way as you would a variable, such as coefficients for a digital filter, it might make sense to declare them as constant variables.

While there are some good reasons to use constant variables in specific circumstances, they should generally be avoided whenever a text substitution created with #define would suffice.