What's the difference between using the variable specifiers static volatile combined? Or using one alone; like static or volatile in microcontroller programming?
static - in this case makes the variable visible only inside the current file. static object have static storage duration.
volatile - it is information for the compiler that the object can be changed by something outside the normal execution path (for example, the interrupt routine) and guarantees that the variable will be read before any use and written after every change. volatile (which is a very common misunderstanding) does not guarantee anything else - no atomicity, no cache coherency, etc., etc.
Many good answers were provided here, but no mention of scope.
Static variables once initialized and later changed within a scope, they retain the changes and never be destroyed or initialized again especially when leaving the scope. Not unless dictated in code. You can say, static variables resemble global variables in terms of their lifecycle but can only be accessed throughout their own scope.
The volatile part has the tendency to force execution to fetch a variable from RAM and not the cached copy in registers or flash. Suppose for example a certain code was submitted to the compiler under certain level of optimization setting. The compiler does not assume any further conditions are attached to variables other than to clear them when they are not used or outside their scope. There are inherently dual uses for volatile, either to disregard optimization offered by the compiler for that variable, or to refrain from using the prefetched copy of that variable except for the one in RAM.
The static volatile is the combination of both behaviors, persistence of that variable in RAM beyond any optimization.
Potential areas of application:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With