C++ Logo


Advanced search

Re: pointer to volatile, but no volatile object

From: David Brown <david_at_[hidden]>
Date: Wed, 7 Jun 2023 16:45:14 +0200
On 06/06/2023 21:40, Thiago Macieira via Std-Discussion wrote:
> On Tuesday, 6 June 2023 02:40:52 PDT David Brown via Std-Discussion wrote:
>> After all, volatile accesses to local non-volatile variables can
>> sometimes be useful in the context of debugging - you can use such
>> accesses to ensure that a variable is actually updated (at least from
>> the viewpoint of the current thread) at a particular point in the code,
>> where you might have placed a breakpoint.
> In my experience, volatile gets (ab)used not for debugging, but to suppress
> some compiler optimisation that the developer didn't want that does have some
> visible side-effect. For example, I've seen it used to force accepting a signed
> integer overflow, because the value had to be re-read from memory. In fact,
> I've seen that in a security training that was given to developers about how
> to remove undefined behaviour from their code... which didn't inspire me with
> confidence.

Without knowing the details of the situation, I agree that this sounds
highly questionable. "volatile" should not be used as a way to try to
turn undefined behaviour into defined behaviour.

> We also (ab)use it in our application at work to force specific codegen from
> the compiler. Our application does some things no normal application does,
> like recalculate the same thing over and over again with the same inputs to
> see if it becomes different.
> Needless to say, all those uses are very fragile and will likely break soon.

I think if you can find a feature in a programming language that cannot
be abused, it is unlikely to have any good uses either!

But I agree that "volatile" is often misunderstood, and often abused -
while at the same time being absolutely essential at the low level. (I
work in small systems embedded programming, where "volatile" is
particular important for correct code - and also where people get it
wrong in many imaginative ways!)

Received on 2023-06-07 14:45:22