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

atmega, avr, c, volatile

Solution

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.

Problem

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?

Original source

Related problems