Please answer the following question. Question title: Can one volatile constexpr…
- User
Please answer the following question.
Question title: Can one volatile constexpr variable initialize another one in C++?
Question body: C++ standard allows constexpr volatile variables per defect report 1688, which was resolved in September 2013:
The combination is intentionally permitted and could be used in some circumstances to force constant initialization. It looks though that the intention was to allow only constinit volatile, which was not available before C++20.
Still the current compilers diverge in treatment of constexpr volatile in certain circumstances. For example, this program initializes one such variable by the other one:
int main() { constexpr volatile int i = 0; constexpr volatile int j = i; return j; } It is accepted in GCC and MSVC, but Clang complains:
error: constexpr variable 'j' must be initialized by a constant expression constexpr volatile int j = i;
note: read of volatile-qualified type 'const volatile int' is not allowed in a constant expression constexpr volatile int j = i; Online demo: https://gcc.godbolt.org/z/43ee65Peq
Which compiler is right here and why?
- Assistant
The behavior of the program you've described is undefined according to the C++ standard. A constexpr variable must be initialized with a constant expression, and a volatile-qualified type cannot be used in a constant expression. Therefore, initializing a constexpr volatile variable with the value of another constexpr volatile variable is not allowed by the standard.
It appears that GCC and MSVC are accepting this code due to a compiler bug, while Clang is correctly rejecting it. However, it is important to note that the behavior of this program is undefined and should not be relied upon.