Constants, or literals, refer to fixed values that a program cannot alter during execution. Constants can be of any basic data type, such as an integer, floating-point number, character, or string.
C has two main types of constants:
- Literal Constants
- Symbolic Constants
Literal Constants
A literal constant is a fixed value written directly in the source code, such as a number, character, or string. It can be assigned to a variable or used directly in an expression.
For example:
int age = 25;
char grade = 'A';
float price = 19.95;
In these examples, 25, ‘A’, and 19.95 are literal constants.
Symbolic Constants
A symbolic constant is an identifier that represents a constant value. Whenever that value is required, the symbolic name can be used instead. This means the value only needs to be specified once when the constant is defined.
Symbolic constants can be defined using the preprocessor directive #define or the const keyword.
Defining Constants Using #define
The #define directive enables simple text substitution. Before the program is compiled, the preprocessor replaces every occurrence of the defined name with its specified value.
For example:
#define PI 3.14
In this example, every occurrence of PI in the source code is replaced by 3.14 during preprocessing.
A #define constant does not have a data type, and the compiler does not treat it as a variable. For this reason, const is often preferred when a typed constant is required.
Defining Constants Using the const Keyword
A variable declared with the const keyword cannot be modified after it has been initialised.
For example:
const float PIVALUE = 22.0 / 7;
Here, PIVALUE is a constant float. Once it has been initialised, the program cannot assign another value to it.
The following example demonstrates both methods of defining a constant:
#include <stdio.h>
#define PI 3.14
int main()
{
const float PIVALUE = 22.0 / 7;
printf("\nValue of const variable PIVALUE: %f", PIVALUE);
printf("\nValue of constant defined with #define: %f", PI);
return 0;
}
The #define constant PI is replaced by 3.14 by the preprocessor, while PIVALUE is a typed const variable.
Constants are often written entirely in uppercase by programmers to distinguish them from ordinary variables. This is a convention, not a requirement.
For example:
#define MAX_SIZE 100
const int MIN_VALUE = 10;
C is case-sensitive, so PI, Pi, and pi are three different identifiers.