假设我执行以下操作:
void g(int* x)
{
int y = 0;
auto diff = uintptr_t(&y) - uintptr_t(x);
}
void f()
{
int x = 0;
g(&x);
}
是否
diff
只是有未定义的值,还是代码调用了未定义的行为?根据规范,代码是否保证运行良好并计算 diff
的值? ,可能没有意义,还是调用UB?我相信有一些关于不相关变量的东西,但无法确定它。我对自(包括)C++ 11 以来的任何标准的答案感兴趣。
讨论来自以下评论:Print stack in C++
最佳答案
引用 C++11 标准草案。关于将指针转换为整数的主题
[expr.reinterpret.cast]
5 A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined.
自
uintptr_t
必须为要编译的代码定义,然后目标机器上存在一个整数类型,它能够成为指针到整数转换的目标。映射是实现定义的,但最重要的是结果不是不确定的。这意味着您为两种转换都获得了一些有效的整数。所以减法不是未定义的行为。但结果是实现定义的。
关于c++ - 计算地址差异是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61757409/