Constant or Final Variables in C Language - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Constant or Final Variables in C Language

Share This

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
#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;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
constants_1
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
constants_2
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.



Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.