https://gcc.gnu.org/bugzilla/show_bug.cgi?id=126359
Bug ID: 126359
Summary: Read of volatile object via a non-volatile glvalue in
constant expression not rejected
Product: gcc
Version: 16.1.1
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: gongke at ios dot ac.cn
Target Milestone: ---
Consider the following code.
```cpp
constexpr int test_volatile_ub() {
volatile int v = 42;
int& ref = const_cast<int&>(v); // cast away volatile
return ref; // UB: reading volatile object through non-volatile glvalue
}
int main() {
constexpr int x = test_volatile_ub(); // force constant evaluation
(void)x;
}
```
[[dcl.type.cv]/5](https://eel.is/c++draft/dcl.type.cv#5):
> If an attempt is made to access an object defined with a volatile-qualified
> type through the use of a non-volatile glvalue, the behavior is undefined
> ([ub:dcl.type.cv.access.volatile]).
So this is an undefined behavior in constant evaluation, which should be
rejected. Clang correctly rejects this, while GCC does not.
[godbolt](https://godbolt.org/z/M891r7fj4)