Dereferencing Typecast Integer Literals

Peter Holzer hp at vmars.tuwien.ac.at
Sun Feb 10 07:59:56 AEST 1991


gwyn at smoke.brl.mil (Doug Gwyn) writes:

>On most Apple II C compilers, this would indeed pick up the data at that
>"soft switch" location.  You need to be aware that in some cases (although
>not likely in this case) the compiler can generate multiple accesses to
>the location even though you have specified it only once in the source
>code.  For I/O registers, including Apple II soft switches, there are
>often side effects from an access, such as clearing a flip-flop, and many
>locations behave differently for read versus write access.  ANSI C has
>introduced the "volatile" type qualifier to provide a handle for the C
>programmer to try to obtain as near to a one-to-one mapping between the
>explicit source code and the generated machine instructions as possible;
>in older C implementations one simply had to be aware of what code would
>be generated for certain C constructs and then make sure that the proper
>constructs were used to obtain the desired effect.  It is still highly
>recommended that you inspect the generated code to make sure that you are
>getting the desired effect.

That reminds me of a deficiency of C for low-level programming, a friend
of mine recently discovered. Volatile tells the compiler that a memory
location might change its value independantly of the program, const
tells the compiler that it may not write to a location, but how do you
tell the compiler that a certain location may not be read? 

In our case the code was something like:

* some_port = value;
shadow = value;

which the compiler "optimized" to:
*some_port = value;
shadow = * some_port;
which caused a bus error :-(

We solved the problem by declaring value volatile, which is extremely
non-obvious and misleading, but does its job.

--
|    _  | Peter J. Holzer                       | Think of it   |
| |_|_) | Technical University Vienna           | as evolution  |
| | |   | Dept. for Real-Time Systems           | in action!    |
| __/   | hp at vmars.tuwien.ac.at                 |     Tony Rand |



More information about the Comp.lang.c mailing list