c - Semantics of volatile -


for sake of question, let @ reads on volatile variables. discussions have read, conclusion multiple reads on same variable declared volatile cannot optimized out single effect.

but believe bit strict. consider 2 reads on variable, not have side effect between them, or not have read of other volatile variable between them.

now know value in volatile variable can change time (without compiler having hint of it). there no way programmer ensure change happen between 2 reads. means both reads seeing same value valid behavior program.

so can't compiler enforce behavior? doing single read , using value twice.

for example

int foo(volatile int * x) {     return *x + *x; } 

can compiler single read in case?

i hope query clear.

also assuming system read doesn't have side effect (like increment of counter, or value changing every read). or such systems exist?

i have looked @ assembly generated gcc , clang , insert 2 reads maximum optimizations. question overly conservative?

edit: not complicate question , avoid confusion implementation defined order of evaluation of sub expressions, can @ example -

int foo(volatile int * x) {     int = *x;     int b = *y;     return + b; } 

but retaining previous example because answers , comments have referenced that.

reading memory location can have side effect. program has use more standard c, of course. reading can have side effect in program relies on implementation-defined behavior.

a common example reading memory-mapped peripheral. on many architectures, main processor exchanges data peripherals when data read or written particular ranges of memory locations. if memory location mapped peripheral, doing 2 reads sends 2 read requests peripheral. peripheral may perform non-idempotent operation on each read.

for example, reading byte serial communication peripheral transfers next byte in peripheral's input queue each time. if foo called address of serial peripheral's byte read register, pulls 2 successive bytes peripheral's read buffer. compiler not allowed change behavior read 1 byte.

well, except behavior undefined because there's no sequence point between reads, , reading volatile side effect. correct function be

int foo2(volatile int *x) {     int x1 = *x;     int x2 = *x;     return x1 + x2; } 

i'd expect compilers generate same code foo foo2 though.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -