User: Password:
Subscribe / Log in / New account

The trouble with volatile

The trouble with volatile

Posted May 15, 2007 9:15 UTC (Tue) by IkeTo (subscriber, #2122)
In reply to: The trouble with volatile by jzbiciak
Parent article: The trouble with volatile

I think the original response says the following simpler code will cause a store plus load:

volatile int a;
void f() {
        a = 2;
The argument is that "a = 2" has a value which requires a load to find, and the compiler is forbidden from optimizing out that load. I don't think the code generated by my 4.1.1 gcc reflects this, however:
        movl    $2, a
So perhaps the OP is speaking from a rather old experience or a different compiler.

(Log in to post comments)

The trouble with volatile

Posted May 15, 2007 12:20 UTC (Tue) by jzbiciak (subscriber, #5246) [Link]

I spoke to the compiler optimizer lead at work. He assures me that assignment ONLY implies a write, even if the value of the assignment expression is used in a subsequent expression.

At least as far as he's concerned, "a = 2" should only compile to a write, and "a = b = 2" should compile to two writes. "a = b = c" should compile to one read (reading 'c'), and two writes (to 'a' and 'b').

That said, our compiler actually compiled "a = b = c" more like "b = c; a = c" (reading 'c' twice), which he indicated was a bug. GCC seems to compile "a = b = c" more like "b = c; a = b", which is actually pretty close to what the OP was suggesting would happen. (Read 'c', Write 'b'. Read 'b', write 'a'.) Fun stuff.

So... a secondary lesson is, "However YOU might have interpreted the C specification, chances are your compiler treats it differently for anything other than the simplest of expressions."

Copyright © 2017, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds