C – Constants with Variables and Macro Definitions
Introduction – Variable Constants and Macro Definitions
In some cases, we want to store a value that cannot be changed. That value would be considered a constant if it never changes throughout the life of a program. Keyword const or macro definition can be used to store constant values, and they can prevent the program from changing those values by mistake. The int data type is used for the constant variable in the code below.
Standard Convention for Naming
The name of the constants should be in uppercase at all times. If constants have multiple words in the name, be sure to separate them with underscores and keep the letters in uppercase. This applies to variables and macro constants.
Similarities and Differences
Keyword const and macro definitions are almost the same thing because they both have the same semantics. But those two operate differently. There are no performance difference between them due to advancement of compilers.
Keyword const is a type of qualifier, and that means that const adds a restriction to the variable. It turns the variable to read-only mode. New values cannot be assigned to them after declaring them a constant, and new values must be given at declaration of the variable. The following code below does not work.
Macro is not a variable since it does not represent a memory space. As a result, do not place that type of constant on the left-hand sign of the equal sign. Whenever a software developer wants to use the constant of that type, he or she would just use its name like using variables. Before the program gets built, C uses a preprocessor (macro’s version of a compiler) that replaces the constant name with its actual value in the C file before compiling. Please refer to the code below for an example.
After preprocessing the C file, the main function becomes like the code below.
The compiler would start executing the code above after preprocessing is complete.
Use constants with const or macro definition if there are values that will never change throughout the life of a program. Constant variables and macros have the same semantics but operate differently. Macro definitions are not variables since it does not represent a memory space. A macro uses a preprocessor to replace constant’s name with its value.