0% found this document useful (0 votes)
47 views1 page

Constant Objects: Example

The const and volatile keywords can modify types in C++. Const creates read-only objects that cannot be modified after initialization. Volatile creates variables that can be modified by external events like interrupts in addition to the program. It is possible to combine const and volatile to declare variables that cannot be modified by the program but can change due to external events.

Uploaded by

MariaNedelcu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views1 page

Constant Objects: Example

The const and volatile keywords can modify types in C++. Const creates read-only objects that cannot be modified after initialization. Volatile creates variables that can be modified by external events like interrupts in addition to the program. It is possible to combine const and volatile to declare variables that cannot be modified by the program but can change due to external events.

Uploaded by

MariaNedelcu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

THE KEYWORDS CONST AND VOLATILE ■ 33

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 defini-
tion.

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 initi-
ated 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 pro-
gram but by external events.

You might also like