Why is volatile needed in C?

volatile in embedded c
volatile in c tutorialspoint
const volatile in c
static volatile in c
const volatile c++
register c
where volatile variable is stored in c
volatile variable java

Why is volatile needed in C? What is it used for? What will it do?

Volatile tells the compiler not to optimize anything that has to do with the volatile variable.

There are at least three common reasons to use it, all involving situations where the value of the variable can change without action from the visible code: When you interface with hardware that changes the value itself; when there's another thread running that also uses the variable; or when there's a signal handler that might change the value of the variable.

Let's say you have a little piece of hardware that is mapped into RAM somewhere and that has two addresses: a command port and a data port:

typedef struct
{
  int command;
  int data;
  int isbusy;
} MyHardwareGadget;

Now you want to send some command:

void SendCommand (MyHardwareGadget * gadget, int command, int data)
{
  // wait while the gadget is busy:
  while (gadget->isbusy)
  {
    // do nothing here.
  }
  // set data first:
  gadget->data    = data;
  // writing the command starts the action:
  gadget->command = command;
}

Looks easy, but it can fail because the compiler is free to change the order in which data and commands are written. This would cause our little gadget to issue commands with the previous data-value. Also take a look at the wait while busy loop. That one will be optimized out. The compiler will try to be clever, read the value of isbusy just once and then go into an infinite loop. That's not what you want.

The way to get around this is to declare the pointer gadget as volatile. This way the compiler is forced to do what you wrote. It can't remove the memory assignments, it can't cache variables in registers and it can't change the order of assignments either:

This is the correct version:

   void SendCommand (volatile MyHardwareGadget * gadget, int command, int data)
    {
      // wait while the gadget is busy:
      while (gadget->isbusy)
      {
        // do nothing here.
      }
      // set data first:
      gadget->data    = data;
      // writing the command starts the action:
      gadget->command = command;
    }

Why is volatile needed in C?, Volatile tells the compiler not to optimize anything that has to do with the volatile variable. There are at least three common reasons to use it,  You aren't alone. The use of volatile is poorly understood by many programmers. Unfortunately, most books about the C programming language dismiss volatile in a sentence or two. [Proper use of volatile is part of the bug-killing Embedded C Coding Standard.] C's volatile keyword is a qualifier that is applied to a variable when it is declared.

volatile in C actually came into existence for the purpose of not caching the values of the variable automatically. It will tell the compiler not to cache the value of this variable. So it will generate code to take the value of the given volatile variable from the main memory every time it encounters it. This mechanism is used because at any time the value can be modified by the OS or any interrupt. So using volatile will help us accessing the value afresh every time.

How to Use C's Volatile Keyword, The proper use of C's volatile keyword is poorly understood by many there is no need to reread it, since the value will (duh!) always be the  For above code, compiler does optimization, that’s why the size of assembly code will reduce. Output: [narendra@ubuntu]$ gcc -O3 volatile.c -o volatile –save-temps [narendra@ubuntu]$ ./volatile Initial value of local : 10 Modified value of local: 10 [narendra@ubuntu]$ ls -l volatile.s -rw-r–r– 1 narendra narendra 626 2016-11-19 16:21 volatile.s

Another use for volatile is signal handlers. If you have code like this:

int quit = 0;
while (!quit)
{
    /* very small loop which is completely visible to the compiler */
}

The compiler is allowed to notice the loop body does not touch the quit variable and convert the loop to a while (true) loop. Even if the quit variable is set on the signal handler for SIGINT and SIGTERM; the compiler has no way to know that.

However, if the quit variable is declared volatile, the compiler is forced to load it every time, because it can be modified elsewhere. This is exactly what you want in this situation.

volatile (computer programming), This is not surprising, as most C texts dismiss it in a sentence or two. variable's value into the accumulator (on the second line), there is no need to reread it,  Other answers have done a very good job explaining why the volatile keyword should be used. Here are some important notes about how to use the volatile keyword.. The volatile keyword, like const, is a qualifier; in fact these are known as cv-qualifiers ("c" = const, "v" = volatile), and they are used in the same ways:

volatile tells the compiler that your variable may be changed by other means, than the code that is accessing it. e.g., it may be a I/O-mapped memory location. If this is not specified in such cases, some variable accesses can be optimised, e.g., its contents can be held in a register, and the memory location not read back in again.

Introduction to the volatile keyword, When need to use volatile keyword. It is very important to understand when to use the volatile keyword in the program.Many programmers know the concept of​  Volatile keyword in c and embedded system I think, you might have heard of Volatile keyword in c and embedded system frequently. But, when it comes to writing code especially in Embedded programming the use of “volatile” keyword is very often.

See this article by Andrei Alexandrescu, "volatile - Multithreaded Programmer's Best Friend"

The volatile keyword was devised to prevent compiler optimizations that might render code incorrect in the presence of certain asynchronous events. For example, if you declare a primitive variable as volatile, the compiler is not permitted to cache it in a register -- a common optimization that would be disastrous if that variable were shared among multiple threads. So the general rule is, if you have variables of primitive type that must be shared among multiple threads, declare those variables volatile. But you can actually do a lot more with this keyword: you can use it to catch code that is not thread safe, and you can do so at compile time. This article shows how it is done; the solution involves a simple smart pointer that also makes it easy to serialize critical sections of code.

The article applies to both C and C++.

Also see the article "C++ and the Perils of Double-Checked Locking" by Scott Meyers and Andrei Alexandrescu:

So when dealing with some memory locations (e.g. memory mapped ports or memory referenced by ISRs [ Interrupt Service Routines ] ), some optimizations must be suspended. volatile exists for specifying special treatment for such locations, specifically: (1) the content of a volatile variable is "unstable" (can change by means unknown to the compiler), (2) all writes to volatile data are "observable" so they must be executed religiously, and (3) all operations on volatile data are executed in the sequence in which they appear in the source code. The first two rules ensure proper reading and writing. The last one allows implementation of I/O protocols that mix input and output. This is informally what C and C++'s volatile guarantees.

Understanding volatile qualifier in C, he volatile field is needed to make sure that multiple threads always see Hopefully C#8 non-nullable discards the last question but so many  Use of volatile qualifier with the structure. A volatile keyword is also useful with user define data types.When we declare a variable of structure volatile then all member of the structure are volatile but sometime in the program, we need only some specific member as volatile so in that situation, we have to declare this member implicitly volatile.

Why Do We Need the Volatile Keyword?, Use cases. volatile is required when. representing hardware registers (or memory-mapped I/O) as variables - even if the register will  To fix this you can use volatile keyword that you can apply to the field. This statement disables the compiler optimizations so you can force the correct order in you code. private static volatile int _flag = 0; You should use volatile only if you really need it, because it disables certain compiler optimizations, it will hurt performance. It's

Using volatile in embedded C development, volatile keyword is a qualifier that is applied to a variable when it is declared. loop i.e. while (1) so that the Machine code to read status isn't needed. C) By turning off all the optimizations, our low level program couldn't  That’s why it’s not so straight forward to have a sample working C program which can easily show-case the exact effect of “volatile” keyword. In fact, in this article, if we could explain the meaning and purpose of ‘ volatile ‘, it would serve as basic groundwork for further study and use of ‘volatile’ in C.

What is volatile keyword?, In such cases, it is possible that some variables are required to be declared as volatile. as volatile . Table 4-5 C code for nonvolatile and volatile buffer loops  Marking a variable as volatile tells the compiler to not "cache" the variable's contents into a processor register, but always read it from memory, when needed. This may slow down processing, which is why you don't just make every variable volatile, when not needed.

Comments
  • http://stackoverflow.com/questions/72552/c-when-has-the-volatile-keyword-ever-helped-you
  • Personally, I'd prefer the integer size to be explicity e.g. int8/int16/int32 when talking to hardware. Nice answer though ;)
  • yes, you should declare things with a fixed register size, but hey - it's just an example.
  • Volatile is also needed in threaded code when you are playing with data that isn't concurrency protected. And yes there are valid times to be doing that, you can for example write a thread safe circular message queue without needing explicit concurrency protection, but it will need volatiles.
  • Read the C specification harder. Volatile only has defined behavior on memory-mapped device I/O or memory touched by an asynchronous interrupting function. It says nothing about threading, and a compiler which optimizes away access to memory touched by multiple threads is conformant.
  • @tolomea : completely wrong. sad 17 persons don't know it. volatile is not a memory fence. it is only related to avoiding code elision during optimization based on assumption of non visible side effects.
  • Came into existence? Wasn't ´volatile` originally borrowed from C++? Well, I seem to remember...
  • This is not volatile all about - it also prohibit some reordering if specified as volatile..
  • @FaceBro: The purpose of volatile was to make it possible for compilers to optimize code while still allowing programmers to achieve the semantics that would be achieved without such optimizations. The authors of the Standard expected that quality implementations would support whatever semantics were useful given their target platforms and application fields, and didn't expect that compiler writers would seek to offer the lowest quality semantics that conform to the Standard and weren't 100% stupid (note that the authors of the Standard explicitly recognize in the rationale...
  • ...that it's possible for an implementation to be conforming without being of good enough quality to actually be suitable for any purpose, but they didn't think it necessary to prevent that).
  • @syntaxerror how can it be borrowed from C++ when C was more than a decade older than C++ (both on first releases and first standards)?
  • when you say "the compiler is forced to load it every time, is it like when compiler decide to optimize a certain variable and we don't declare the variable as volatile, at run time that certain variable is loaded to CPU registers not in memory?
  • @AmitSinghTomar It means what it says: Every time the code checks the value, it is reloaded. Otherwise, the compiler is allowed to assume that functions that don't take a reference to the variable can't modify it, so assuming as CesarB intended that the above loop does not set quit, the compiler can optimise it into a constant loop, assuming that there's no way for quit to be changed between iterations. N.B.: This isn't necessarily a good substitute for actual threadsafe programming.
  • if quit is a global variable, then the compiler shall not optimize the while loop, correct ?