Optimization is typically controlled via compiler settings - such as the compiler command line. It is not controlled in code.
However for doing optimization the compiler assumes that variables behave like "normal variables" while the code is not interrupted.
This may lead to the following error: Some example code:
int a;
void myFunc(void)
{
a=1;
/* Wait until the interrupt sets a back to 0 */
while(a==1);
}
void interruptHandler(void)
{
/* Some hardware interrupt */
if(a==1) doSomeAction();
a=0;
}
The compiler assumes that there are no interrupts. Therefore it would see that
- "a" is set to 1 and never changed before the "while" loop
- The while loop is an endless loop because "a" does not change whithin this loop
- "a" is never read before this endless loop
Therefore the optimizing compiler may change the code internally like this:
void myFunc(void)
{
while(1);
}
Leaving the "volatile" away may work but may not work.
If you do not have hardware interrupts (and no parallel threads, multi-core CPUs etc.) "volatile" makes the code only slower and has no benefit because it is not required.