Perhaps char* allowed an alias that anything included volatile memory.
With the -fpermissive flag -fpermissive gcc just displays a warning about char* pointing to volatile memory, but compiles .
Since in your example the pointer is extern , it may use a different translation compiled with this flag, so the pointer points to volatile memory. Therefore, optimization cannot be performed.
I did not find an official link to whether char* aliasing volatile nonvolatile memory is considered legitimate or UB.
EDIT: It appears that the same warning is given for the int* to volatile int* assignment, in which case the compiler does the optimization. Therefore, I assume that warning / enabling flags are not related. The only question is whether char* generally allowed for the volatile alias in general.
Here's an example of smart clearing a volatile struct using C ++ with no warnings only.
EDIT2: It seems that adding the -fno-strict-aliasing flag -fno-strict-aliasing that any type of pointer is not optimized in the source code. Therefore, I think the reason compilers do not optimize when they fear aliases. Or because:
- Flashing
volatile memory allowed (?) - Fear of data racing with other pointers to the same non-volatile memory. @alain mentions in his answer that the data races are UB, but even if this is true, I think that the compiler developers decided to be careful here, not optimize.
Danra source share