Yahoo Groups archive

AVR-Chat

Index last updated: 2026-04-28 22:41 UTC

Message

Re: gcc compiler bad behaviour

2012-04-16 by bayramdavies

Tim Mitchell wrote:

> OK Thanks for the clarifications about volatile ... the
> variable in question was ... being ... changed in mainline
> code ... [and] being *read* in an interrupt routine. As
> the compiler couldn't see the variable being used in the
> current scope it optimised the code out.

Great.  Your explanation is exactly correct.

> ... the compiler has only optimised part of it, it is
> still loading the value into a register, but then has
> removed the store instruction. If it had optimised the
> whole thing away it would seem a slightly more valid
> thing to do.

By declaring AdcVal[] as volatile, you are instructing the compiler to evaluate accesses to elements of this array "strictly according to the rules of the abstract machine".  In terms we can understand, this means not performing any optimizations that would remove or re-order accesses to the object.  So, although the compiler is not interested in the value of AdcVal[0] and AdcVal[1], it is obliged to read the objects.  This would be important if, for example, the read operations had hardware side-effects, such as clearing the A-to-D interrupt.  This is why you should always declare hardware registers (or more accurately, special function registers) as volatile, without trying to out-think Don's simple guidelines.

Graham Davies
ECROS Technology
www.ecrostech.com

Attachments

Move to quarantaine

This moves the raw source file on disk only. The archive index is not changed automatically, so you still need to run a manual refresh afterward.