• Home
  • 1.7 Constants (const)

1.7 Constants (const)

View Categories

1.7 Constants (const)

< 1 min read

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 named PI and initializes it with the value 3.14159.
  • The const keyword makes the object read-only. Its value cannot be changed after initialization.
  • A const object 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.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *