Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Volatile keyword in C [duplicate]

Tags:

c

volatile

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?


2 Answers

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.

like image 71
unwind Avatar answered Nov 23 '25 05:11

unwind


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.

like image 30
Alex Avatar answered Nov 23 '25 07:11

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!