使用数组索引时的操作顺序

发布于 2024-12-08 13:02:31 字数 325 浏览 4 评论 0原文

考虑这个循环:

int[] myArray = new int[10];

int myIndex = 0;
for (int i = 0; i < 10; i++)
{
    myArray[myIndex++] = myIndex;
    Console.WriteLine(myArray[i]);
}

这会产生:

1
2
3
...

因为 myIndex 是后递增的,并且首先评估右侧,所以数组索引 0 不应该包含 0 吗?

有人能为我解释一下这种操作顺序的误解吗?

Consider this loop:

int[] myArray = new int[10];

int myIndex = 0;
for (int i = 0; i < 10; i++)
{
    myArray[myIndex++] = myIndex;
    Console.WriteLine(myArray[i]);
}

This yields:

1
2
3
...

Because myIndex is post-incremented, and the right side is evaluated first, shouldn't the array index 0 contain 0?

Can someone explain this order-of-operations misunderstanding for me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

剑心龙吟 2024-12-15 13:02:31

不一定首先评估右侧。类似:

foo.Bar.Baz = a + b;

在上面的代码中,首先评估foo.Bar,然后评估a + b,然后调用set_Baz方法来设置Baz 属性为右侧评估的任何内容。

所以在你的代码中,如果你把它分成几部分,它看起来像这样:

var index = i;
// post-incremented in the original code means this comes after the line above,
// but not after the line below it.
i += 1; 
myArray[index] = i;

The right side isn't necessarily evaluated first. Similar to:

foo.Bar.Baz = a + b;

In the above code, foo.Bar is evaluated first, then a + b, then the set_Baz method is called to set the Baz property to whatever is evaluated on the right.

So in your code, if you break it into pieces, it looks like this:

var index = i;
// post-incremented in the original code means this comes after the line above,
// but not after the line below it.
i += 1; 
myArray[index] = i;
鸠书 2024-12-15 13:02:31

第一次运行:

myArray[myIndex++] = myIndex;
           *            *
           |            |
         zero          one

myIndex++myArray[myIndex++] 之后执行,但任何后续调用都具有已经递增的变量。

first run:

myArray[myIndex++] = myIndex;
           *            *
           |            |
         zero          one

myIndex++ gets executed after myArray[myIndex++], but any subsequent calls with have the already incremented variable.

Hello爱情风 2024-12-15 13:02:31

myIndex++ 在设置值之前执行,因为数组索引优先,因此它知道将值设置为哪个数组索引。

The myIndex++ is executing before the value is being set because the array index takes precident so it knows what array index to set the value to.

娇俏 2024-12-15 13:02:31

...

myArray[myIndex++] = myIndex;

...相当于...

int tmp = myIndex;
++myIndex;
myArray[tmp] = myIndex;

The...

myArray[myIndex++] = myIndex;

...is equivalend to...

int tmp = myIndex;
++myIndex;
myArray[tmp] = myIndex;
演多会厌 2024-12-15 13:02:31

根据优先级,首先计算 myIndex++,然后是左侧,最后是赋值运算符

The myIndex++ is evaluated first, followed by the left side and finally the assign operator, according to precedence

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文