【发布时间】:2023-03-11 01:05:01
【问题描述】:
以下程序在形式上是正确的 C++ 吗?
#include <iostream>
#define CASE 1
#if CASE==1
constexpr void* crash = static_cast<void*>(static_cast<char*>(nullptr)+1);
#elif CASE==2
constexpr void* crash = nullptr;
#elif CASE==3
const void* crash = static_cast<void*>(static_cast<char*>(nullptr)+1);
#endif
int main() {
std::cout << "Crash: " << crash << "\n";
}
G++ 8.4.0 报告
error: reinterpret_cast from integer to pointer
constexpr void* crash = static_cast<void*>(static_cast<char*>(nullptr)+1);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Visual Studio 19 cl 报告:
null.cc(3): error C2131: expression did not evaluate to a constant
null.cc(3): note: failure was caused by unevaluable pointer value
如何解释这些错误消息?
如果我将 CASE 的值更改为 2 或 3,则两个编译器的编译都会成功,并且运行已编译的程序会给出预期的结果。
【问题讨论】: