5

I am writing program for ARM with Linux environment. its not a low level program, say app level

Can you clarify me what is the difference between,

int iData;

vs

volatile int iData;

Does it have hardware specific impact ?

1 Answers1

-1

volatile in C came into existence for the purpose of not caching the values of the variable automatically. It will tell the machine not to cache the value of this variable. So it will 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.

Read the Wiki and this page for more explanation

Jainendra
  • 24,713
  • 30
  • 122
  • 169
  • Your ans looks great. thank you Jaguar.. I have another doubt, do we need volatile in case of a non cache machine ? –  Apr 10 '13 at 05:35
  • You do need `volatile` even without memory cache, once you have more than one register in your processor. Because the `volatile` keyword also says to the compiler : don't keep that value in a register, always fetch it from memory... For instance, signal handlers often set a `volatile sigatomic_t` flag... – Basile Starynkevitch Apr 10 '13 at 06:17
  • 2
    Sorry but thats wrong, volatile does not prevent the MACHINE to cache anything. It prevents the COMPILER from keeping a variable in a register. Broadly said, it disables CSE and a couple of other optimizations for this variable. – Nico Erfurth Apr 10 '13 at 06:18
  • Yes, I meant that `volatile` is only for the compiler, and may have worded that wrongly – Basile Starynkevitch Apr 10 '13 at 06:24
  • How it will tell the machine not to cache? Volatile doesn't do any multicore visibility assurance also. – auselen Apr 10 '13 at 09:08
  • It's basically saying to the compiler, "I'm smarter than you so don't try any optimization tricks of your own and do what I tell you to, when I tell you to." – tangrs Apr 11 '13 at 00:36