Russ Meyerriecks wrote:
I'm willing to admit that I don't fully understand where volatile
goes. Not only would it be very noble of someone to explain this to
us, but I'm certain that he would be rained with fame, women, and
money for his efforts.
I'd help, but I suspect you are not being entirely honest about the
potential rewards.
Russ
On 11/4/05, *Steve Underwood* <ste...@coppice.org
<mailto:ste...@coppice.org>> wrote:
>>6. Avoid using volatiles, unless they are really necessary.
>>
>>
>
>No one would ever declare a variable volatile unless there was a
good reason to. Are you saying that the compiler can
>optimise better with variables which aren't volatile? That's
normal for any compiler AFAIK.
>
>
Do you have any idea how small a percentage of embedded C programmers
understand what volatile really means, and where it is needed?
Oh, OK.
What happens if I do this?
int i;
interrupt (TIMERA0_VECTOR) int_routine(void)
{
i = 42;
}
void func(void)
{
i = 0;
while (i == 0);
}
Let's assume here that interrupts are working, and "func" is called. If
you are used to poorly optimising compilers you might expect "func" to
return after a timer A interrupt. With GCC and no optimisation "func"
will return (I am not sure if that is certain to happen, but it always
seems to work). However, turn on optimisation, and GCC will strip out
whatever it can. For example, it could hold "i" in a register within
"func", and never see the change cause within the interrupt routine. It
could go further, figuring out that nothing is every going to happen in
that loop, and strip out the test of i completely, leaving an infinite
loop. If I want to tell GCC that it must look at the actual memory
location of i each time it checks or manipulates i, I need to declare i
as "volatile int i;". Then, we can be sure "func" will respond as
required when the interrupt routine alters i.
The other side of this is that if we start using "volatile" too
liberally we loose significant efficiency. Instead of doing lots of fast
compact register only work, the compiler is forced to go to the real
memory location for everything it does with variables marked volatile.
In most cases that is pure waste, making things bigger and slower than
necessary.
volatile is your friend. Use it wisely, and the really smart compilers
will do what you want.
Regards,
Steve