3

I'm currently learning C in class and I'm having some confusion understanding volatile variables. My textbook (Computer Programming, by Ajay K. Mittal, Ashok N. Kamthane and Anita Goel) defines them as follows:

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?

wovano
  • 4,543
  • 5
  • 22
  • 49
Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91
  • 6
    In general, volatile variables are used in embedded systems. The point is to tell the compiler that these variables can change; that the usual assumptions the compiler makes about variables don't apply to volatile variables. – Charlie Burns Nov 17 '13 at 04:36
  • You might wanna check: http://stackoverflow.com/questions/1665452/volatile-variable – Sinn Nov 17 '13 at 04:37

2 Answers2

9

volatile keyword tells the compiler that the variable can be changed (sounds senseless) so you should take care while optimizing. For example consider this-

bool running = true;
while(running) {
    //do something
}

The compiler may change while(running) to while(1) but if the variable running is being affected by the code outside the while loop, like in multi-threading, this will create a bug very hard to spot. So the correct thing would be to declare running as volatile.

volatile bool running = true;
while(running) {
    //do something
}
Shubham
  • 935
  • 1
  • 7
  • 25
  • 2
    In multithreading, you use a condition variable or mutex around `running`. Those constructs may be implemented using `volatile` or they may not, but it's not really a user-level tool. – Potatoswatter Nov 17 '13 at 05:19
9

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.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421