the volatile keyword in C language? [duplicate]

Solution 1:

The statement "the value can be changed by means outside of this code" basically means that another program or hardware can update that variable. This is totally possible. One way of thinking of this is by relating this concept to a file that is shared among multiple programs. A file can be opened, written, and read by many programs at once. When you read from a file you want to make sure that you are reading the latest update and not the oldest.

Going back to the volatile keyword, placing volatile before a variable, in effect, does the same thing. It makes sure that what you are reading out of the variable isn't based on the compiler's optimization or an old copy of the variable that your program had. Moreover, the volatile keyword ensures that the variable is fetched from memory on every access. Therefore, both of those statements are correct regarding the volatile keyword.

Solution 2:

C isn't necessarily for computers. For example, if you're developing for the Game Boy Advance, you often come upon memory locations that are modified by the hardware, so you might not modify the variable in your code, but it gets modified anyway. That's what volatile means.

By adding the volatile keyword, you're telling the compiler that "The value stored in this variable (memory location) might change without my code doing anything."

Solution 3:

Consider any of the following:

  • a multi-threaded application,
  • an application using shared memory,
  • an application running on a platform that maps I/O registers into the address space,
  • an application with hardware DMA occurring in the background.

In each of these situations, memory can be altered outside the current thread.

Note that "anytime the value of a variable is change in register, then the value should affect the memory" is correct, just not very clear.