5.9.6 Accessing Objects From Interrupt Routines

Reading or writing objects from interrupt routines can be unsafe if other functions access these same objects.

The compiler will automatically treat as volatile any variables that are referenced in an interrupt routine, unless they are an initialized object qualified as const; however, it is recommended that you explicitly mark these variables using the volatile specifier to ensure your code is portable (see 5.3.8.2 Volatile Type Qualifier). The compiler will restrict the optimizations performed on volatile objects (see 5.13 Optimizations).

Even when objects are marked as volatile, the compiler cannot guarantee that they will be accessed atomically. This is particularly true of operations on multi-byte objects, but many operations on single-byte or bit objects cannot be performed in one instruction.

Interrupts should be disabled around any main-line code that modifies an object that is used by interrupt functions, unless you can guarantee that the access is atomic. Check the assembler list file to see the code generated for a statement, but remember that the instructions can change as the program is developed, particularly if the optimizers are enabled.