代码之家  ›  专栏  ›  技术社区  ›  danben

后增量运算符:意外行为[重复]

  •  8
  • danben  · 技术社区  · 14 年前

    可能重复:
    Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)

    我的代码如下:

    #include <stdio.h>
    int main()
    {
      int x = 10, y = 0;
      x = x++;
      printf("x: %d\n", x);
      y = x++;
      printf("y: %d\n", y);
    }
    

    考虑到后增量的性质,我希望得到以下输出:

    x: 10
    y: 10
    

    我的理由是在第5行, x 应该在增量发生后分配给它的初始值。

    然而,我得到的是:

    x: 11
    y: 11
    

    在大会上,我认为这是一个深思熟虑的选择:

    LCFI2:
            movl    $10, -4(%rbp)   // this is x
            movl    $0, -8(%rbp)    // this is y
            incl    -4(%rbp)        // x is simply incremented
            movl    -4(%rbp), %esi
            leaq    LC0(%rip), %rdi
            movl    $0, %eax
            call    _printf
            movl    -4(%rbp), %eax  // now x is saved in a register,
            movl    %eax, -8(%rbp)  // copied to y,
            incl    -4(%rbp)        // and finally incremented
            movl    -8(%rbp), %esi
            leaq    LC1(%rip), %rdi
            movl    $0, %eax
            call    _printf
    

    这是怎么回事?海湾合作委员会是想救我脱离自己吗?我手边没有语言参考,但我认为这会破坏预期的语义。

    4 回复  |  直到 14 年前
        1
  •  13
  •   Georg Fritzsche    14 年前

    该行为未定义,因为在 x = x++ ,参见 C FAQ .

        2
  •  4
  •   Thanatos    14 年前

    C语言没有定义什么时候会发生post/pre-in/decrement。因此,如 x = x++ 没有很好的形成-避免它们。

        3
  •  2
  •   Mark Rushakoff    14 年前

    撇开标准不谈(因为这对标准没有定义),它的运行方式就是我所期望的。

    我的经验法则是 x++ ,你代替 x++ 具有 x x += 1 在下一行(或前一行用于预增量)。

    根据经验法则,您的代码将被编写为

    #include <stdio.h>
    int main()
    {
      int x = 10, y = 0;
      x = x; // x: 10
      x += 1; // x: 11
      printf("x: %d\n", x);
      y = x; // y: 11
      x += 1; // x: 12
      printf("y: %d\n", y);
    }
    
        4
  •  1
  •   functional    14 年前

    当你拥有:

    a = b++;
    

    发生的是B被保存到A中,并且在分配完成后,B将增加1。所以如果你这样做:

    x = x ++;
    

    以前的x是10,会发生的是10会保存到x,之后(在打印完成之前)x会增加1到11。这就是为什么要印刷11。