Constant variable:
Constant variable is a variable whose value cannot be changed during the execution of the program. And if we try to change the value, an error will get generated.
Syntax:
const datatype variable=value;
A constant is declared using the keyword “const”.
Example:
const int a=10; valid
const a=10;
a=20; //error
A constant has to be initialized at the time of declaration.
(i) const int a=10; //valid
(ii) const int a; //invalid
a=10;
Question:Which of the following is better and why?
(a). float pi=3.1415;
(b). const float pi=3.1415;
Sol:
(b) is better as it declares pi as constant. If we try to change the value it will generate an error.