What is const and volatile qualifier in C programming?


Value of any variable can be changed either by program or external device. Keywords const and volatile are not opposite to each other.

Const:

When any variable has qualified with const keyword in declaration statement then it is not possible to assign any value or modify it by the program. But indirectly with the help of pointer its value can be changed.
When any variable is not qualified by const variable then
its default qualifier is not const .There is not any keyword for not const. Its meaning is that value of variable can be changed after the declaration statement by the program. Example:

What will be output of following program?

#include<stdio.h>
int main(){
const int a=5;
a++;
printf(“%d”,a);
return 0;
}

Output: 
Compiler error, we cannot modify const variable.

Volatile:

When any variable has qualified by volatile keyword in declaration statement then value of variable can be changed by any external device or hardware interrupt. If any variable has not qualified by volatile keyword in declaration statement, then compiler will take not volatile as default quantifier .There is not any special keyword for not volatile. Not volatile means when any variable has qualified by volatile keyword in declaration statement then value of variable cannot be changed by any external device or hardware interrupt.

What is meaning of the declaration:

const volatile int a=6;

Answer:
Value of variable cannot be changed by program (due to const) but its value can be changed by external device or hardware interrupt (due to volatile).

7 comments:

sandeep sengar said...

nice

Anonymous said...

superb...... this site is very helpful for C language..... I like this site.........

priyanka mane said...

its in simple language.....thank you

Anonymous said...

it is very simple language......thank you.

Anonymous said...

great job

Naveen Kumar said...

very simple and easy explanation..

Unknown said...

Thanks for article.
Nice explaination