1.

What is volatile in C?

Answer»

Volatile is a keyword in C that tells the compiler not to optimize anything that is related to the volatile variable and always fetch the value of the variable from the memory for every use of the volatile variable.

For example, 

int RUN = 1;while(run){ // Do something and don't involve run variable at all}

In this case, the compiler sees that the variable run is not being used at all in the loop and hence can optimize the while loop into while(1). But run can be changed by a signal handler or OS etc. If we make the variable run as volatile, then the compiler doesn't do any such optimization.

The 3 major places where volatile is used (i.e., variable can change without action from visible CODE) is:

  • Interface with hardware that changes the value itself (I/O MAPPED memory LOCATION).
  • Another thread running that also uses the same variable.
  • A signal handler that might change the value.


Discussion

No Comment Found