Author Topic: volatile  (Read 206 times)

Offline beingchinmayTopic starter

  • Trade Count: (0)
  • Semi-Newbie
  • *
  • Thank You 0
  • Posts: 34
  • Karma: 0
  • Gender: Male
  • I am Chinmay
    • Fat Cutter
« on: 09-15-2016, 07:23:35 »
The volatile qualifier tells the compiler that a variable’s value may be changed in ways not explicitly specified by the program. For example, the address of a global variable may be passed to an interrupt-driven clock routine that updates the variable with each tick of the clock. In this situation, the contents of the variable are altered without the use of any explicit assignment statements in the program. The reason the external alteration of a variable may be important is that a C++ compiler is permitted to optimize certain expressions on the assumption that the content of a variable is unchanged if it does not occur on the left side of an assignment statement. However, if factors external to the program change the value of a variable, then problems can occur.

For example, in the following fragment, assume that clock is being updated every millisecond by the computer’s clock mechanism. However, since clock is not declared as volatile, the fragment may not always work properly. (Pay special attention to the lines labeled A and B.)