Text Substitution Labels

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:

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.

© 2024 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.