C++ Constants
In C++, a constant is a value that cannot be changed during the execution of a program. Once a constant is defined, its value remains the same throughout the program.
Using the const Keyword
The const keyword is used to declare constant variables.
const int age = 25;
In this example, the value of age cannot be changed after it is defined.
Example Program
#include <iostream>
using namespace std;
int main() {
const float PI = 3.14159;
cout << "Value of PI: " << PI;
return 0;
}
Output
Value of PI: 3.14159
Using #define for Constants
Constants can also be defined using the #define preprocessor directive.
#define PI 3.14159
This method defines a constant value before the program is compiled.
Example Using #define
#include <iostream>
using namespace std;
#define PI 3.14159
int main() {
cout << "Value of PI: " << PI;
return 0;
}
Rules for Constants
- The value of a constant cannot be changed after declaration.
- Constants must be initialized when they are declared.
- Constant names are usually written in uppercase to distinguish them from variables.
Advantages of Constants
- Improves code readability.
- Prevents accidental modification of important values.
- Makes programs easier to maintain.
Next Topic
Next, learn about C++ Operators.