In C, a constant is a value that cannot be changed during the execution of a program. Constants can be defined using the #define
preprocessor directive or the const
keyword.
The #define
directive is used to define a constant value that can be used throughout the program. The syntax is as follows:
#define constant_name value
For example:
#define PI 3.14159
This defines a constant named PI with a value of 3.14159.
The const
keyword is used to declare a variable as constant. The syntax is as follows:
const type variable_name = value;
For example:
const int MAX = 100;
This declares a constant integer variable named MAX with a value of 100.
Constants can be used in expressions and assignments, just like variables. For example:
int radius = 5; float circumference = 2 * PI * radius;
In this example, the constant PI is used in the expression to calculate the circumference of a circle with a radius of 5.
Using constants in C can help make programs more readable and maintainable by avoiding the use of “magic numbers” and hard-coded values throughout the code.