首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GCC常量表达式允许加法,但不允许与地址进行逐位或

GCC常量表达式允许加法,但不允许与地址进行逐位或
EN

Stack Overflow用户
提问于 2019-11-19 11:21:38
回答 1查看 170关注 0票数 7

考虑下面的代码:

代码语言:javascript
复制
#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 (所有版本4-9)可以很好地编译arithmetic(),但拒绝使用bitwise()

代码语言:javascript
复制
<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;
      |                                         ~~~~~~~~~~~~~~~~^~~~

为什么?请注意,在其他常量表达式用例中,按位或可以很好地工作,但在这个用例中就不行。

演示:https://godbolt.org/z/x5jbuU

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-22 14:33:58

根本不能在常量表达式中使用reinterpret_cast (或执行此操作的C风格的强制转换)。GCC要么有一个强制执行的bug,要么是试图帮助支持一些与+相关而不是|相关的实际用例。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58926138

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档