C – Constants with Variables and Macro Definitions
Introduction – Variable Constants and Macro Definitions
In some cases, we want to store a value that we do not want to modify. That value would be considered a constant if it never changes. We can use keyword const or macro definition to store constant values. We are going to use int as the data type for the constant variable in the code below.
Standard Convention for Naming
The name of constants need to be in uppercase. If you have multiple words in the name, be sure to separate them with underscores and keep the letters 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. This means that const adds a restriction to the variable. It turns the variable to read-only mode. You cannot assign new values to them after declaring constant variables. You must give them value as you declare them. 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 we want to use the constant of that type, we use its name like how we do with variables. When we build the program, 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 will start executing the code above.
Use constants with const or macro definition if you want to store constant values. 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.