Table of Contents
A constant is an object whose value cannot be modified after it has been initialized. In C++, the const keyword is used to declare read-only variables.
This example demonstrates how to declare a constant and use it in a program.
Source Code #
#include <iostream>
int main()
{
const float PI = 3.14159f;
std::cout << "Value of PI: " << PI << '\n';
return 0;
}
Output #
Value of PI: 3.14159
Explanation #
const float PI = 3.14159f;declares a constant namedPIand initializes it with the value3.14159.- The
constkeyword makes the object read-only. Its value cannot be changed after initialization. - A
constobject must be initialized when it is declared. - Constant names are commonly written in uppercase to distinguish them from regular variables. This is a naming convention and is not enforced by the language.
std::cout << "Value of PI: " << PI << '\n';prints the value stored in the constant.return 0;terminates the program successfully.