C Programming Text Substitution Labels

Last modified by Microchip on 2023/11/09 09:07

In most cases, constants are used for the convenience of the person writing the code or for those who will read the code later. In this capacity, constants are used to replace magic numbers, to make code more readable, and to make it easier during the development process to modify a value that is used in many places throughout the program.

This kind of constant need not reside in the PIC® microcontroller's memory in the same way that a variable does. Instead, it is something that can be handled at compile time as a text substitution.

#define label text

Because this is a preprocessor operation (all directives starting with a # are instructions to the C preprocessor), everything this line does is finished before the program is passed on to the compiler. The preprocessor will replace every instance of label with text. The preprocessor doesn't care about variable types, numbers, characters, or anything else related to C's syntax in this situation. It simply does a text substitution. So, if you had something like:

1    #define PI 3.14159

Every place the preprocessor finds PI in your source file, it will replace it with the text 3.14159. It doesn't matter what the context is. Once all these substitutions are made, the code then gets passed to the compiler where it decides how to interpret the text 3.14159. (In this case, the text would be interpreted as a double-precision floating point value.)

The primary benefit of using #define text substitutions for constants is that they have no impact on memory usage. So, for exactly zero overhead, you can replace every magic number with its own unique, descriptive name/label while improving the efficiency (and sanity) of any developer who must read your code, especially your future self.