I read that volatile is used when we want to store variables in SRAM.

But aren't all the variables in a code are stored in SRAM anyway?

And what makes it an advantage sometimes for variables(like volatile) to be stored in SRAM?


That's just plain incorrect.

The volatile keyword tells the compiler that the value of that variable may change at any time, and that therefore it must re-read the value every time you use it in your code.

If you don't use volatile, the compiler may choose to make an optimisation.

Consider this code:

int b = 7; 
a = b + b;

The compiler can see that 'b' is always 7 -- it is assigned the value 7 and nobody ever changes it. The compiler may choose to optimise this to the equivalent of

a = 14;

But if you do this:

volatile int b = 7;
a = b + b;

then the compiler MUST read b twice from memory.

Why would you want to do that? Perhaps you have an interrupt which might change the value of b. Perhaps your interrupt changes the value of 'b' every time you press a button. You need the code to really check the value of b every time it calculates a, and not rely on it always being 7.

Here is a fuller explanation.

  • Can you a bit expound on why volatile is better to use with interrupts?
    – floppy380
    Jan 23 '17 at 13:36
  • I've tried and added a bit more information, but I'm not quite sure what more you'd like to know. Is there a particular thing you don't understand? (I'm aware that it's often hard to state clearly what one doesn't understand.)
    – Mark Smith
    Jan 23 '17 at 13:58

Technically, variables can be stored anywhere, in SRAM, eeprom or enev flash.

However, without doing anything special, variables are stored in SRAM.

Thee votike attribute is just that, it tells the compiler that the variable could change its value and the compiler shouldn't assume that values obtained from prior access is valid now. This forces the compiler to re-read the variable on demand.

  • "Thee votike" ?
    – Gerben
    Jan 23 '17 at 18:43
  • Local variables are most often stored in CPU registers, although in some cases they can end up in RAM. Jan 23 '17 at 21:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.