1

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?

asked Jan 23, 2017 at 12:06

2 Answers 2

4

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.

answered Jan 23, 2017 at 12:14
2
  • Can you a bit expound on why volatile is better to use with interrupts? Commented Jan 23, 2017 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.) Commented Jan 23, 2017 at 13:58
1

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.

answered Jan 23, 2017 at 12:16
2
  • "Thee votike" ? Commented Jan 23, 2017 at 18:43
  • Local variables are most often stored in CPU registers, although in some cases they can end up in RAM. Commented Jan 23, 2017 at 21:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.