Properties of Constant in C
The important properties of constant variables in C defined using the const keyword are as follows:
1. 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.
2. 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.
C
// C Program to demonstrate the behaviour of constant // variable #include <stdio.h> 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;
| ^
Constants in C
The constants in C are the read-only variables whose values cannot be modified once they are declared in the C program. The type of constant can be an integer constant, a floating pointer constant, a string constant, or a character constant. In C language, the const keyword is used to define the constants.
In this article, we will discuss about the constants in C programming, ways to define constants in C, types of constants in C, their properties and the difference between literals and constants.