avr-gcc-list
[Top][All Lists]

## Re: [avr-gcc-list] "Volatile"

 From: Dave Hansen Subject: Re: [avr-gcc-list] "Volatile" Date: Mon, 18 Apr 2005 09:56:13 -0400

```From: Dean Hall <address@hidden>
[...]
```
Using volatile can then become confusing for a trivial fragment such as this:
```        volatile v = 42;
v = ((v=12) | (~v) | (!v));
```
Does this cause two loads of v? Is v equal to twelve or forty two when ~v is executed? Answers are left as an exercise to the reader.
```
1) Yes (two writes to v).
2) The last value written to v is 1.  The expression (~v) is never executed,
```
and the compiler is free to refuse to generate code for it, or for the (!v).
```   The value of v is not known to the compiler.

```
But let me give this advice to all: when declaring a volatile variable, use it only in very simple statements. In the embedded space, especially when dealing with volatile, it is a good programming practice to break complex actions into multiple lines of simple statements. This makes things clear to the reader and assists debugging.
```
Agreed.

```
I still argue that, given volatile b, the expression "a = b = 0;" requires the compiler to clear "b", read "b", and store the result in "a" rather than simply clearing a and b. The committee disagrees. But the point is really moot: if there is a reason "b" is volatile, treat it with more respect to guarantee it is handled the way you require rather than employing stupid code tricks.
```
[...]

```
Also be aware that the compiler is within its right to convert the line "v = 42;" into two, three, or N identical store instructions,
```
```
Is this the same (volatile) v? If so, then no, it is not. If v is volatile, this expression must cause a single access to v, no more, no less.
```
If v is not volatile, you are correct.

```
The only wiggle room the standard gives here is that what constitutes an "access" to a voltatile variable is implementation-defined.
```
Regards,
-=Dave

```