在 cppreference 上我看到了 ub 的说法i = ++i + i++
,记得在编译阶段似乎无法执行带有 ub 的代码,我决定通过抛出一些简单的代码来检查一下:
#include <iostream>
constexpr int func(int i){
i = ++i + i++;
return i;
}
constexpr int glob_i = func(1);
int main()
{
std::cout << glob_i << "\n"; // выводит 4
return 0;
}
我不明白为什么这不会导致编译错误?如果编译通过,为什么运行时的类似计算会给出结果 5?
godbolt 上的示例:https://godbolt.org/z/rM8b7szz5
cppreference 上的文章,一切从这里开始https://en.cppreference.com/w/cpp/language/eval_order