Symbolic Constants
Symbolic Constants
Labels (names) that represent fixed values that never change during the course of a program.

What Are Constants?

Symbolic constants are what most people think of when someone refers to "constants" in any program language. Symbolic constants are nothing more than a label or name that is used to represent some fixed value that never changes throughout the course of a program. For example, one might define PI as a constant to represent the value 3.14159.

Why Do We Need Constants?

Avoid Magic Numbers

Magic numbers are literals that get used in your code without any obvious reason. For example, if I have a line of code like:

Why is the value of 0x30 used here? Why not 0x31 or 0xBEEF? What is the significance of that particular value? Only the programmer knows, and he has likely forgotten. A better approach is to build a description into the value by creating a named/symbolic constant and using it in place of the raw value:

Where ASCII_OFFSET is defined somewhere in the program to have a value of 0x30.

Even if you don't know what is meant by "ASCII_OFFSET", you at least have some clue as to what its purpose is so you can ask the right questions.

Quickly Change Values During Development

When developing a complex program, there may be situations where you need to calibrate or otherwise tweak your constant values until the system works the way you expect. For example, say you have a delay routine used all over your program that you need to play with to get the timing right before releasing your code. If you load a counter register with a value like 255 everywhere you use the delay, it would be very cumbersome to change the value in multiple locations. If on the other hand you create a constant called DELAY_COUNT and use it everywhere you use the delay, changing the value is as easy as changing the constant's definition.

How to Define Constants

There are two ways to create constants in C that we will look at over the next two pages:

© 2016 Microchip Technology, Inc.
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.