C++ Programs Const Keyword
In C++, the const
keyword is used to indicate that a value is a constant and cannot be modified. Constants are useful when you want to define a value that should not change throughout the program execution.
Syntax
const data_type variable_name = value;
In the above syntax, data_type
can be any valid C++ data type, and variable_name
can be any valid C++ identifier. The value of a constant variable cannot be changed once it is declared.
Example
#include <iostream>
using namespace std;
int main() {
const int x = 10; // declare constant variable
// x = 20; // this line will cause a compilation error
cout << x << endl;
return 0;
}
Output
10
Explanation
In the above example, we have declared a constant variable x
and assigned it the value 10. Since x
is a constant, we cannot change its value in the program. If we try to modify the value of x
, the program will fail to compile.
Use
Constants are used in C++ programs to define values that do not need to be changed during program execution. They are especially useful when you need to define a fixed value that multiple parts of your program can reference.
#include <iostream>
using namespace std;
const float PI = 3.14159;
float circle_area(float radius) {
return PI * radius * radius;
}
int main() {
float r = 5;
float area = circle_area(r);
cout << "The area of the circle is: " << area << endl;
return 0;
}
In the above example, we have defined a constant PI
and used it in a function to calculate the area of a circle. The value of PI
is fixed and will not change during program execution.
Important Points
- Constants are values that cannot be changed during program execution
- The
const
keyword is used to declare a constant variable - The value of a constant variable cannot be changed after it is declared
- Constants can be used to define fixed values that multiple parts of the program can reference
Summary
In summary, the const
keyword is used in C++ programs to define constant values that cannot be changed during program execution. Constants are useful when you need to define a fixed value that multiple parts of your program can reference.