【问题标题】:Is this example causing an undefined behaviour? [duplicate]此示例是否导致未定义的行为? [复制]
【发布时间】:2011-05-26 08:43:09
【问题描述】:

可能重复:
Undefined Behavior and Sequence Points

变量i 更改了两次,但下一个示例会导致未定义的行为吗?

#include <iostream>
int main()
{
    int i = 5;
    std::cout << "before i=" << i << std::endl;
    ++ i %= 4;
    std::cout << "after i=" << i << std::endl;
}

我得到的输出是:

before i=5
after i=2

【问题讨论】:

    标签: c++ undefined-behavior language-lawyer


    【解决方案1】:

    是的,它是未定义的。赋值时没有序列点,% 或 ++ 并且您不能在一个序列点内多次更改变量。

    编译器可以将其评估为:

    ++i;
    i = i % 4;
    

    i = i % 4;
    ++i;
    

    (或其他)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多