"Forcing read/write to memory" is very different from "not caching the value in a register". Optimizations can involve not just caching values in registers, but also reordering operations, calculating things at compile-time and so on.
For a trivial example, see this code:
int f() {
int sum = 0;
for (int i = 0; i < 10; i++) sum += i;
return sum;
}
As you can see from [1], a smart compiler will calculate the sum at compile time and make the function simply return the resulting number (i.e., no loop is generated).
If you make "sum" volatile, the compiler is forced to do the loop[2].
For a trivial example, see this code:
As you can see from [1], a smart compiler will calculate the sum at compile time and make the function simply return the resulting number (i.e., no loop is generated).If you make "sum" volatile, the compiler is forced to do the loop[2].
[1] https://godbolt.org/z/3sX5mU
[2] https://godbolt.org/z/F5CiDJ