Consider this code:
#include <cstdint>
static int x = 0;
const uintptr_t arithmetic()
{
static constexpr uintptr_t result = ((uintptr_t)&x) + 1u;
return result;
}
const uintptr_t bitwise()
{
static constexpr uintptr_t result = ((uintptr_t)&x) | 1u;
return result;
}
GCC (all versions 4-9) compiles arithmetic()
just fine, but rejects bitwise()
:
<source>: In function 'const uintptr_t bitwise()':
<source>:13:57: error: '(((uintptr_t)(& x)) | 1)' is not a constant expression
13 | static constexpr uintptr_t result = ((uintptr_t)&x) | 1u;
| ~~~~~~~~~~~~~~~~^~~~
Why? Note that bitwise-or works fine in other constexpr use cases, but not this one.
Demo: https://godbolt.org/z/x5jbuU
You can’t use reinterpret_cast
(or a C-style cast that performs one) in a constant expression at all. GCC either has a bug enforcing that, or is trying to be helpful to support some practical use case where +
but not |
is relevant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With