C has some basic data types like 'int', 'float', 'char' etc. Each of which can hold a data of a specific type and has a set of specific properties defined for them. But what if you need to modify the properties of them? For example, if you want to make an 'int' variable constant, that means it's value shouldn't be changed from any where else in the program except the variable definition part. C type qualifiers can be used for such purposes.
'Const' Qualifier in C
Two type qualifiers available in C are 'const' and 'volatile'.
'Const' qualifier will impose a restriction on the variable, such a way that its value can't be changed or modified. The main use of 'const' is to define constants in your program; so that it's values can't be changed. Please take a look at the example given below to understand the use case of 'const' qualifier
- #include <stdio.h>
- // PI is defined as 'const' so that you may not change it's value accidentally.
- const float PI = 3.14;
- double find_area(float radius) {
- return PI * radius * radius;
- }
- int main() {
- printf("Area: %f", find_area(5.5));
- return 0;
- }
- Output:
- Area: 94.985001
'Volatile' Type Qualifier in C
If a variable is declared as 'volatile', its value can be changed from outside the program. Declaring a variable with 'volatile' is actually a hint to the compiler to not perform any optimizations on the access restrictions of the variable. Let's take a look at it with the help of an example using 'volatile' keyword.