Sri Harsha Chilakapati Sri Harsha Chilakapati - 2 months ago 15
C Question

Understanding volatile variables in C

I'm currently learning C in class and I'm having some confusion understanding volatile variables. My textbook defines them as this.

Volatile Variables


The volatile variables are those variables that are changed at any time by other external
program or the same program. The syntax is as follows.
volatile int d;



What is exactly the difference between the normal variables and volatile variables? If volatile variables can be changed by external programs, how can I change the value from another external program.

Thanks.

Answer

volatile indicates that the bytes used to store an object may be changed or accessed by something else running in parallel with the program. In practice this is usually a hardware interface, but sometimes it is used to interface with the operating system as well.

Whereas const indicates that memory is read-only (to your program), volatile indicates that some other task has write access to it. const volatile together indicate that an object represents a hardwired input; you might see such a thing in a microcontroller with a memory-mapped sensor.

How this affects your program is that the compiler treats accesses to the memory specially. If you access it twice, the compiler will not cache the first access and give you the same value twice. It will go to the memory hardware and perform two read operations. And when you modify the object, that modification is written immediately and exactly as you specify, with no buffering or reordering optimizations.

Comments