assume you have an timer interrupt handler which sest a global variable every second, e.g.
Code:
volatile int second=0; // set every second
void __attribute__((__interrupt__, __shadow__)) _T1Interrupt(void)
{
/* Interrupt Service Routine code goes here */
IFS0bits.T1IF = 0; //Reset Timer1 interrupt flag
second=1;
}
int main(void)
{
...
startTimer();
second=0;
while(!second); // wait 1 second
... // code executed after a second
}
in main second is tested in the while() statement which executes every second
the problem is that if second is not declared volatile an optimising compiler will look at
Code:
second=0;
while(!second) ; // wait 1 second
see that second is initialised to 0 and remove the while() statement - thus whole sections of code can be removed
the volatile keyword tells the compiler that the variable may be altered outside the current context and code should not be optimised
for more detail see
https://en.cppreference.com/w/cpp/language/cv