I know there are a lot of questions regarding volatile here but I haven't found anything specific to this case. I am working with a microcontroller. I know I have to use the volatile qualifier when I modify a global variable inside an ISR and read it inside my main function. I also feel quite fit with memory barriers, race conditions etc.
But what if I only write to a global variable in my main function(with interrupts being disabled to enforce an atomic write) and i am reading and writing it inside my ISR.
To give a clear example assume this code:
int state = 0;
ISR()
{
switch(state)
{
case 0:
//do something
state=nextState; //go to another state
break;
case 1:
//do something
state=nextState; //go to another state
break;
case 2:
//do something
state=nextState; //go to another state
break;
//...some more states
default:
state=0;
break;
}
}
main(void)
{
while(true)
{
//do lots of stuff
if(someCondition)
{
EnterCriticalSection(); //Disable IRQs and memorybarrier
//write to global shared variable state here!!!
state=0;
ExitCriticalSection(); //Enable IRQs again
}
}
}
So must state be volatile here?
And when, why? (I am never really using the value inside the main) Can the compiler optimize the write to state away or something. Or can the compiler keep the value of state cached in some Register across multiple callings of the ISR? For now I keep variables like state volatile but I am curious if this is actually necessary.
Edit: Well, yes I understand the answers now. I apologize, I should have thought about it some minutes more. When I think about it now it is quite similar to (write-only) hardware registers. Of course I need volatile here to ensure a write operation in the main method.