Weddington, Eric wrote:
IIRC it said volatile must be used to keep the compiler from optimizing
away access to a variable that he thinks might be pointless. Like
writing a variable that is never read back.


The way volatile was explained to me many years ago, is that a variable must be declared 
as "volatile" if it's value can be changed by something outside of the mainline 
code. This boils down to two use cases:
- A memory location that can be changed by hardware (i.e. a register)
- A memory location that can be changed by an interrupt service routine (ISR).

third case: if you use a multi-threaded operating system and a memory location is modified by at least one thread and read by other threads (one may also need a lock mechanism in such a case)

fourth case: nasty situations where 'volatile' is only a part of the solution but does not insure a correct result:

For instance if ISR1 and ISR2 are *nested* ISRs, IsrCounter does not correctly hold the count of interrupts:

volatile uint8_t IsrCounter;

ISR1()
{
     IsrCounter++;
}

ISR2()
{
     IsrCounter++;
}

Consider also memory locations larger than the MCU data processing unit size (8 bits for AVR).

The following code gives bad results on an AVR but works on a i386:

volatile uint32_t MilliSeconds;

ISR()
{
   MilliSeconds++;
}

main()
{
   while(MilliSeconds < SOME_LIMIT) ...
}

   Bernard


_______________________________________________
AVR-GCC-list mailing list
[email protected]
http://lists.nongnu.org/mailman/listinfo/avr-gcc-list

Reply via email to