1

I am writing program for ARM in a Linux environment. It’s not a low-level program, say on the application level.

What is the difference between the following?

int iData;

vs

volatile int iData;

Does it have a hardware-specific impact?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

7 Answers7

7

Basically, volatile tells the compiler "the value here might be changed by something external to this program".

It's useful when you're (for instance) dealing with hardware registers, that often change "on their own", or when passing data to/from interrupts.

The point is that it tells the compiler that each access of the variable in the C code must generate a "real" access to the relevant address, it can't be buffered or held in a register since then you wouldn't "see" changes done by external parties.

For regular application-level code, volatile should never be needed unless (of course) you're interacting with something a lot lower-level.

unwind
  • 391,730
  • 64
  • 469
  • 606
4

The volatile keyword specifies that variable can be modified at any moment not by a program.

If we are talking about embedded, then it can be e.g. hardware state register. The value that it contains may be modified by the hardware at any unpredictable moment.

That is why, from the compiler point of view that means that compiler is forbidden to apply optimizations on this variable, as any kind of assumption is wrong and can cause unpredictable result on the program execution.

Alex
  • 9,891
  • 11
  • 53
  • 87
2

By making a variable volatile, every time you access the variable, you force the CPU to fetch it from memory rather than from a cache. This is helpful in multithreaded programs where many threads could reuse the value of a variable in a cache. To prevent such reuse ( in multithreaded program) volatile keyword is used. This ensures that any read or write to an volatile variable is stable (not cached)

arunmoezhi
  • 3,082
  • 6
  • 35
  • 54
0

Generally speaking, the volatile keyword is intended to prevent the compiler from applying any optimizations on the code that assume values of variables cannot change "on their own."

(from Wikipedia)

Now, what does this mean?

If you have a variable that could have its contents changed at any time, usually due to another thread acting on it while you are possibly referencing this variable in a main thread, then you may wish to mark it as volatile. This is because typically a variable's contents can be "depended on" with certainty for the scope and nature of the context in which the variable is used. But if code outside your scope or thread is also affecting the variable, your program needs to know to expect this and query the variable's true contents whenever necessary, more than the normal.

This is a simplification of what is going on, of course, but I doubt you will need to use volatile in most programming tasks.

Jerome Baldridge
  • 518
  • 2
  • 13
0

In the following example, global_data is not explicitly modified. so when the optimization is done, compiler thinks that, it is not going to modified anyway. so it assigns global_data with 0. And uses 0, whereever global_data is used.

But actually global_data updated through some other process/method(say through ptrace ). by using volatile you can force it to read always from memory. so you can get updated result.

#include <stdio.h>    
volatile int global_data = 0;

int main()
{

FILE *fp = NULL;
int data = 0;    
printf("\n Address of global_data:%x \n", &global_data);

        while(1)
        {
              if(global_data == 0)
                {                    
                      continue;
                }
                else if(global_data == 2)
                {
                        ;
                        break;
                }
        }    

return 0;
}
Jeyaram
  • 9,158
  • 7
  • 41
  • 63
0

volatile keyword can be used,

when the object is a memory mapped io port.

An 8 bit memory mapped io port at physical address 0x15 can be declared as
char const ptr = (char *) 0x15;
Suppose that we want to change the value at that port at periodic intervals. 
*ptr = 0 ;
while(*ptr){
*ptr = 4;//Setting a value
*ptr = 0; // Clearing after setting
}
 It may get optimized as
*ptr = 0 ;
while(0){
}

Volatile supress the compiler optimization and compiler assumes that tha value can be changed at any time even if no explicit code modify it. Volatile char *const ptr = (volatile char * )0x15;

Used when the object is a modified by ISR.

Sometimes ISR may change tha values used in the mainline codes

static int num;
void interrupt(void){ 
++num;
}
int main(){
int val;
val = num;
while(val != num)
val = num;
return val;
}

Here the compiler do some optimizations to the while statement.ie the compiler
produce the code it such a way that the value of num will always read form the cpu registers instead of reading from the memory.The while statement will always be
false.But in actual scenario the valu of num may get changed in the ISR and it will reflect in the memory.So if the variable is declared as volatile the compiler will know
that the value should always read from the memory

user2247801
  • 145
  • 3
0

volatile means that variables value could be change any time by any external source. in GCC if we dont use volatile than it optimize the code which is sometimes gives unwanted behavior.

For example if we try to get real time from an external real time clock and if we don't use volatile there then what compiler do is it will always display the value which is stored in cpu register so it will not work the way we want. if we use volatile keyword there then every time it will read from the real time clock so it will serve our purpose....

But as u said you are not dealing with any low level hardware programming then i don't think you need to use volatile anywhere

thanks

umang2203
  • 78
  • 5