Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC constexpr allows add but not bitwise-or with address

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

like image 291
John Zwinck Avatar asked Nov 19 '19 03:11

John Zwinck


1 Answers

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.

like image 87
Davis Herring Avatar answered Sep 28 '22 18:09

Davis Herring