Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad if all variables are defined as volatile on AVR programming?

I read that in some cases (global variable, or while(variable), etc.) if the variables are not defined as volatile it may cause problems.

Would it cause a problem if I define all variables as volatile?

like image 845
Johan Elmander Avatar asked Jul 17 '13 19:07

Johan Elmander


People also ask

What happens when a variable is declared as volatile?

Volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time-without any action being taken by the code the compiler finds nearby.

Why volatile is bad?

A highly volatile security hits new highs and lows quickly, moves erratically, and has rapid increases and dramatic falls. Because people tend to experience the pain of loss more acutely than the joy of gain, a volatile stock that moves up as often as it does down may still seem like an unnecessarily risky proposition.

Why do we declare variable as volatile?

volatile is a keyword that must be used when declaring any variable that will reference a device register. If this is not done, the compile-time optimizer might optimize important accesses away. This is important; neglecting to use volatile can result in bugs that are difficult to track down.

Can you have constant volatile variable?

Yes a C++ variable be both const and volatile. It is used in situations like a read-only hardware register, or an output of another thread. Volatile means it may be changed by something external to the current thread and Const means that you do not write to it (in that program that is using the const declaration).


1 Answers

If something outside of the current scope or any subsequent child scope (think: function calls) can modify the variable you are working in (there's a timer interrupt that will increment your variable, you gave a reference to the var to some other code that might do something in response to an interrupt, etc) then the variable should be declared volatile.

volatile is a hint to the compiler that says, "something else might change this variable." and the compiler's response is, "Oh. OK. I will never trust a copy of this variable I have in a register or on the stack. Every time I need to use this variable I will read it from memory because my copy in a register could be out of date."

Declaring everything volatile will make your code slow down a lot and result in a much larger binary. Instead of doing this the correct answer is to understand what needs to be tagged volatile, why it does, and tagging appropriately.

like image 198
Chris Raplee Avatar answered Oct 02 '22 22:10

Chris Raplee