【问题标题】:Why is this if with initializer not true?如果初始化程序不正确,为什么会这样?
【发布时间】:2020-05-29 11:25:54
【问题描述】:
int* get(){return nullptr;}

int main()
{
   if(auto p = get(); (*p) != 1231231233)
   {
        std::cout << "NO";   // not printed
   }
   else
   {
        std::cout << "we should be here" << std::endl;;   
   }
}

为什么这里没有打印NO,因为根据standardinit-statement 没有检查为真并且对*p 的访问应该是UB,我们应该得到在true ?.我很疑惑: LIVE

【问题讨论】:

  • 你为什么认为UB会导致true? “真”是已定义的行为,而 UB 是未定义的行为。
  • 我再次忘记了 UB 会发生什么……
  • @Gabriel 如果答案解决了您的问题,请将其标记为已接受。
  • 请在标签中包含 [c++] 以及具体版本

标签: c++ if-statement c++17 c++20


【解决方案1】:

您正在取消引用 if-clause 中的 nullptr,这是未定义的行为。基本上允许编译器对那段代码做它想做的任何事情。您无法对执行(*p) 时会发生什么做出任何假设。

【讨论】:

  • 我才发现。谢谢。
猜你喜欢
  • 2012-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 2012-08-09
  • 1970-01-01
相关资源
最近更新 更多