Constants in C are fixed values which cannot be changed during the execution of the program. In C, we can declare variables as constants in two ways. They are:
1) By using “const” keyword
2) By using “#define” preprocessor directive
We can declare a variable as a constant by using the const qualifier. A variable that is declared using const cannot change its value once it is initialized. The syntax of using the const is as shown below:
Example of using the const keyword is as shown below:
#define Preprocessor Directive
We can also declare constants in a program by using the #define preprocessor directive. Such constants declared using the #define preprocessor directive are known as symbolic constants. The syntax of using #define is as shown below:
Example of using #define is shown below:
Take care that there is no semi-colon (;) at the end of #define statement. In the above example we have assigned the value 3.142 to the symbol PI. Now, whenever PI is encountered in the program, it will be replaced with the value 3.142.
Following are the rules that apply to a #define statement:
1) All rules that apply to variables also apply to symbolic name. Generally symbolic names are written in CAPTIAL LETTERS, to distinguish them from the normal variable names.
2) No blank space between # and define is allowed.
3) # must be the first character in the #define statement.
4) A blank space is required between #define and the symbolic name and between symbolic name and the value.
5) #define statements must not end with a semi-colon.
6) After declaring a symbolic constant, we must not use it in an assignment statement.
7) Symbolic names are not declared for data types. Its data type depends on the type of the constant value.
8) #define statements may appear anywhere in the program, but before they are referenced in the program. Generally they are placed at the top of the program after the #include statements.
const Vs #define
The purpose of both const and #define is to declare constants in a C program. The difference between them is: when we declare a variable as a constant using const, it is still treated as a variable but the value will be fixed and cannot be changed. But, when we use #define, we are declaring symbolic constants, which are not treated as variables. Instead the compiler searches for the symbol throughout the program and replaces the symbol with the value. Another difference is, const is a keyword, where as #define is a preprocessor directive.
ANSI standard defines another qualifier volatile that could be used to tell the compiler that a variable’s value may be changed at any time by some external sources (from outside the program). Example usage of the volatile keyword is shown below:
The value of date can be modified by its own program too. If you don’t want the program to modify the value of date variable, but it can be modified by external factors, then date can be declared as both volatile and const as shown below: