views:

596

answers:

4
+2  Q: 

Volatile variable

Where is a volatile variable stored in the stored in program memory(in which section) ?

+6  A: 

The volatility of a variable does not change the place in which a variable is stored. What it changes is the semantics around how it is accessed with respect to reads and writes.

I do not believe the C standard says anything about the implementation of volatile. But typically, volatile guarantees release semantics for write operations on a variable and aquire semantics on read operations of a variable. This will not be true for every implementation though and you should read up on what your specific compiler guarantees

JaredPar
no, it does NOT give those semantics see [this](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2016.html) and [CERT](https://www.securecoding.cert.org/confluence/display/seccode/POS03-C.+Do+not+use+volatile+as+a+synchronization+primitive) saying 'don't use `volatile` for synchronization'
Spudd86
+1  A: 

There's no reason for a volatile variable to be stored in any "special" section of memory. It is normally stored together with any other variables, including non-volatile ones. If some compiler decides to store volatile variables in some special section of memory - there's nothing to prevent it from doing so. But at the language level there's absolutely no reason for this.

Why are you asking such a question? What made you think that it should be stored in some special section of memory?

AndreyT
+2  A: 

In C volatile just tells the compiler - "You don't have enough knowledge to assume the value of this variable hasn't changed". There is no "section" eg BSS, CSS for it.

Consider it a flag to the compiler to prevent certain types of optimisations. Its very handy in embedded programming, where memory at a certain address may "change" due to a hardware device input.

Here's a good explanation: http://www.embedded.com/columns/programmingpointers/174300478?_requestid=137658

Justicle
+4  A: 

volatile is a type qualifier not a storage class specifier, so it does not determine storage location at all; it affects the definition of a variable's type, not its storage.

It simply forces the compiler to explicitly read a variable whose type is volatile from the variable's storage location (wherever that may be) rather than assuming that some previously read value in a register for example remains valid.

Clifford