Qualifiers are nothing but an addition of a prefix keyword with existing datatypes to add some extra feature in a declared variable.
There are two qualifiers in C –
const keyword is used to make some variable constant in the program.
Example:
1.int x=5;
x is an integer variable which holds some data 5 and it can be changed to some other value anywhere in the program.
2. const int x=5;
x is a constant integer variable which holds some data 5 and it can not be changed to some other value anywhere in the program.
1. ‘const‘ keyword can use with all data types whether is fundamental or derived.
1 2 3 4 5 6 7 8 9 10 |
const char ch='A'; const unsigned int i_var=3637; const float f_var =3.4546; const int arr_var[5]={10,20,30,40,50}; const struct employee { char name[20]; unsigned long int empId; double salary; }emp={"Amit",4546777,86564.456}; |
2. const keyword freezes the data after initialization and you
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include<stdio.h> const struct employee { char name[20]; unsigned long int empId; double salary; }emp={"Amit",4546777,86564.456}; int main() { /*here i have tried to modify empId*/ emp.empId=353698; return 0; } |
1 2 3 4 5 6 |
Output: In function 'main': error: assignment of member 'empId' in read-only object emp.empId=353698; ^ |
We can see that empId is constant so it can only read but not write.
3. const variable without initialization can freeze itself with some garbage data and it can’t be changed later at runtime.
1 2 3 4 5 6 7 8 |
#include<stdio.h> int main() { const unsigned int x; x=10; return 0; } |
1 2 3 4 5 |
Output: In function 'main': error: assignment of read-only variable 'x' x=10; ^ |
volatile keyword mostly used with the variable which can expect change from outside word also i.e by external peripheral or some other thread.
volatile
keyword tells the compiler not to optimise code related the variable usually, when we know it can be changed from “outside”.
volatile unsigned int vui_var;
A compiler can not optimize the volatile variable i.e every time variable access from its real memory location not from cache or somewhere else.
The volatile variable may also have const qualifier if someone doesn’t want to modify in a program.But this variable can change from outside peripheral or thread e.g status register
1 2 3 4 5 6 7 8 9 |
#include<stdio.h> int main() { volatile const int vi_var=10; //vi_var=50; /*it can't be change inside program*/ printf("vi_var=%d\n",vi_var); return 0; } |