C Programming Language supports to declare a variable for which value can not be changed in run-time. Hence, it should be initialized at the time of declaration, it can not be initialized later.
#include <stdio.h>
int main(void)
{
const int max = 10;
printf("%d\n", max);
//max = 5; can not be changed....
printf("%d\n", max);
return 0;
}
If the variable is not initialized at the time of declaration, 0 is assigned to it as default value for integer, floating point number as well as character.
#include <stdio.h>
int main(void)
{
const int x;
const float f;
const char c;
printf("%d\n", x);
printf("%f\n", f);
printf("%d\n", c);
//x = 5; can not be changed....
//f = 2.0; can not be changed....
//c = 'A'; can not be changed....
return 0;
}
Hence, if you need a variable, which should not be changed during execution, you can declare it as constant. For example, the variable PI=3.142 can be declared as constant.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.