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?
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?
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.
A volatile variable must have its memory accesses honoured by the compiler.
This means that:
Note that volatile
is not (always) sufficient for communication between threads (or between main loops and interrupt service routines: https://stackoverflow.com/a/2485177/106092. See also https://www.kernel.org/doc/Documentation/volatile-considered-harmful.txt
Only make things volatile which need to be. If you find yourself having to make things volatile to make them work it comes down to one of two things:
In my experience it's almost always the latter, but you might need to consult a c-lawyer on why!
But in answer to your actual question, if you make everything volatile, the code should still work fine, although you may have performance limitations that you don't need to have!
A variable is said to be volatile if its value can change at any moment independently of the program. It is useful if another program (or thread), or an external event (keyboard, network ...) can modify the variable. It tells the compiler to reread the value of the variable from its original location each time the variable is accessed. It prevents the compiler to optimize memory access. So declaring each variable volatile may slow down the program.
By the way: I know nothing about specificity of AVR programming.
If you need to configure all variable as volatile , then there is some deep rooted design issue with your software. Yes, it will decrease by performance. But how much? We don't know unless you provide the spec of the CPU and its instructions.