I = I +不会增加我。为什么? [英] i = i++ doesn't increment i. Why?

查看:203
本文介绍了I = I +不会增加我。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能显示的文件:结果
  为什么这个进入一个无限循环?

之类的东西 I = I + 具有不确定的C和C ++的行为,因为一个标对象的值是变化的两倍相同的前pression内中间没有顺序点

Things like i = i++ have undefined behavior in C and C++ because the value of a scalar object is changes twice within the same expression without intervening sequence point.

不过我想,这几样前pressions已经明确定义在C#或Java的行为,因为据我所知论证的评价那张左到右,有顺序分全部结束。

However I suppose that these kind of expressions have well-defined behavior in C# or Java because AFAIK the evaluation of argument goes left to right and there are sequence points all over.

这是说,我期望 I = I ++ 等同于我++ 。但事实并非如此。下面的程序输出 0

That said, I'd expect i = i++ to be equivalent to i++. But it's not. The following program outputs 0.

using System;
class Program
{
    static void Main(string[] args)
    {
        int i = 0;
        i = i++;
        Console.WriteLine(i);
    }
}

你能告诉我为什么?

Could you help me understand why?

声明:
我充分认识到,上述结构的行为是否被定义,他们是愚蠢的,无用的,不可读的,不必要的,不应该在code使用。我只是好奇。

Disclaimer: I am fully aware that whether or not the behavior of above-mentioned constructs is defined, they are silly, useless, unreadable, unnecessary and should not be used in code. I am just curious.

推荐答案

的行为以及在C#中定义和评价顺序是:

The behavior is well defined in C# and the evaluation order is:


  1. 左侧 I 进行评估,以变量 I

  2. 右键侧被评估为0和 I 递增(现在我== 1

  3. 执行分配,它集 I 0(现在我== 0

  1. Left side i is evaluated to the variable i
  2. Right side is evaluated to 0, and i is incremented (now i==1)
  3. The assignment is executed, it sets i to 0. (now i==0)

最终的结果是我== 0

在一般首先要创建一个前pression树。对其进行评估你在根评价第一左侧,然后右侧和最后的操作。这样做递归。

In general you first create an expression tree. To evaluate it you evaluate first the left side, then the right side and finally the operation at the root. Do that recursively.

这篇关于I = I +不会增加我。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆