This Article IsCreated at 2024-03-06Last Modified at 2024-03-06Referenced as ia.www.f23

Compiler May Optimize Memory Access Away

If you have some code that looks like this:

int* ptr_a = some_extern_function();
*ptr_a = 1;
*ptr_a = 2;

The compiler will remove *ptr_a = 1; because it only respects the final state of memory. That’s why you need volatile of writing to memory triggers I/O.

Reading from memory will be optimized away by the same logic. If the result isn’t used anywhere, the read doesn’t have to happen.