The Keywords const And volatile


 

The Keywords const And volatile

Sample program

// Circumference and area of a circle with radius 2.5
 
#include <iostream>
using namespace std;
   
const double pi = 3.141593;
   
int main()
{
   double area, circuit, radius = 1.5;
   
   area = pi * radius * radius;
   circuit = 2 * pi * radius;
   
   cout << "\nTo Evaluate a Circle\n" << endl;
   
   cout << "Radius:        " << radius    << endl
        << "Circumference: " << circuit   << endl
        << "Area:          " << area      << endl;
   
   return 0;
} 

Note 
By default cout outputs a floating-point number with a maximum of 6 decimal places without trailing zeros.

Screen output

To Evaluate a Circle
 
Radius:         1.5
Circumference:  9.42478
Area:           7.06858 
A type can be modified using the const and volatile keywords.

Constant Objects

The const keyword is used to create a "read only" object. As an object of this type is constant, it cannot be modified at a later stage and must be initialized during its definition.
Example:
const double pi = 3.1415947; 
Thus the value of pi cannot be modified by the program. Even a statement such as the following will merely result in an error message:
pi = pi + 2.0;               // invalid 

Volatile Objects

The keyword volatile, which is rarely used, creates variables that can be modified not only by the program but also by other programs and external events. Events can be initiated by interrupts or by a hardware clock, for example.
Example:
volatile unsigned long  clock_ticks; 
Even if the program itself does not modify the variable, the compiler must assume that the value of the variable has changed since it was last accessed. The compiler therefore creates machine code to read the value of the variable whenever it is accessed instead of repeatedly using a value that has been read at a prior stage.
It is also possible to combine the keywords const and volatile when declaring a variable.
Example:
volatile const unsigned time_to_live; 
Based on this declaration, the variable time_to_live cannot be modified by the program but by external events.

Post a Comment

0 Comments