[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [avr-gcc-list] memcpy() : problem when passing destination pointer

From: Graham Davies
Subject: Re: [avr-gcc-list] memcpy() : problem when passing destination pointer
Date: Tue, 10 Feb 2009 21:30:30 -0500

Vincent Trouilliez wrote:

... I was writing to a buffer from an ISR, but it was not read
in that C file, only from a different one, hence invisible to the
compiler. So my understading was: "in that particular file, GCC sees
that I am writing to the buffer, but never reading it, so he might
think it's useless to write to it ! So I added the volatile keyword ...

Is my understanding of volatile wrong ?

Unfortunately, yes. The compiler is allowed to optimize away stuff only if it can be "certain" that the entire program will operate in the same way. The compiler is not allowed to conclude that a variable is not accessed elsewhere in the program just because it can't see that access in one particular translation unit. The canonical example of where volatile is needed is the busy-wait loop on a variable that is written in a different context, i.e. do {} while ( flag == 0 ); where flag is set to one in an interrupt. The problem is not that the compiler can't see that flag is accessed in a different translation unit. The problem is that it can't see that such an access can occur at the same time as the do ... while loop is executing. The compiler reasons that as there is nothing inside the loop that changes flag, then the value of flag never changes once the loop is entered and so only needs to be tested once. If it is zero, the loop will run forever. So, flag must be declared volatile to tell the compiler to produce the repeating test.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]