A constant in C is a user-assigned name to a location in the memory, whose value cannot be modified once declared. This is in contrast to a variable in C, which is also a named memory location, however whose value may be changed during the course of the code.
Instead of repeatedly using hard-coded values in a program, it is advised to define a constant and use it. Constants in a C program are usually employed to refer to a value which may be error-prone if it is to be used repetitively in the program, at the same time its value is not likely to change.
There are two aways to declare a constant in C:
- Using the const Keyword
- Using the #define Directive
Defining Constant Using const Keyword
We define a constant in C language using the const keyword. Also known as a const type qualifier, the const keyword is placed at the start of the variable declaration to declare that variable as a constant.
Syntax
const data_type var_name = value;
Example
#include
int main()
{
// declaring a constant variable
const int var;
// initializing constant variable var after declaration
var = 20;
printf("Value of var: %d", var);
return 0;
}
Output
Printing value of Integer Constant: 25
Printing value of Character Constant: A
Printing value of Float Constant: 15.660000
Defining Constant Using #define Directive
We can also define a constant in C using #define preprocessor. The constants defined using #define are macros that behave like a constant. These constants are not handled by the compiler, they are handled by the preprocessor and are replaced by their value before compilation.
Syntax
#define const_name value
Example
#include
#define pi 3.14
int main()
{
printf("The value of pi: %.2f", pi);
return 0;
}
Output
The value of pi: 3.14
Properties of Constant in C
- Initialization with Declaration: We can only initialize the constant variable in C at the time of its declaration. Otherwise, it will store the garbage value.
- Immutability: The constant variables in c are immutable after its definition, i.e., they can be initialized only once in the whole program. After that, we cannot modify the value stored inside that variable.
Example
#include
int main()
{
// declaring a constant variable
const int var;
// initializing constant variable var after declaration
var = 20;
printf("Value of var: %d", var);
return 0;
}
Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^