5.2 Variable Updated Within An Interrupt Service Routine

Variables that are changed inside ISRs need to be declared volatile. When using the optimizer, in a loop like the following one:

uint8_t flag;
...
ISR(SOME_vect) {
    flag = 1;
}
...
    while (flag == 0) {
        ...
    }

the compiler will typically access "flag" only once, and optimize further accesses completely away, since its code path analysis shows that nothing inside the loop could change the value of "flag" anyway. To tell the compiler that this variable could be changed outside the scope of its code path analysis (e. g. within an interrupt service routine), the variable needs to be declared like:

volatile uint8_t flag;

When the variable is declared volatile as above the compiler makes certain that when the variable is updated or read it will always write changes back to SRAM memory and read the variable from SRAM.