Search code examples
cvolatile

Volatile keyword in C


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?


Solution

  • 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.