C – Constants with Variables and Macro Definitions

Course Outline  | Previous LessonNext Lesson

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.

const int VARIABLE = 20;     // Variable way

/* Macro way, and it is usually placed on top of C file. 
   No semi-colons needed to end a macro statement */
#define CONSTANT_NAME 20

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

const int VARIABLE = 20;     // This is the only way to store constant value to memory

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.

const int VARIABLE;
VARIABLE = 20;          // Error occurs

Macro Definitions

#define CONSTANT_NAME 20

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.

#define CONSTANT 20

int main(void)
{
     int variable = CONSTANT;
     return 0;
}

After preprocessing the C file, the main function becomes like the code below.

int main(void)
{
     int variable = 20;
     return 0;
}

The compiler will start executing the code above.

Conclusion

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.

Course Outline  | Previous LessonNext Lesson

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz