1

for一部のCに似た言語では、ステートメントの更新部分で複数のステートメントを使用できます。

for (int i = 0; i < limit; i++, butter--, syrup--, pancakesDevoured++)

Javaは、ECMA-334(C#)のJLS 14.14.1.2および15.8.3で、このようなステートメントの順序を明示的に定義しています。右に。

ループの更新部分で複数のステートメントを許可しているforが、そのようなステートメントの順序を定義していないか、左から右以外の順序を使用している言語はどれですか?

編集:Cそれがシーケンスポイントの議論を開始したのでタグを削除しました、そしてそれ すでにたくさんあります。

4

1 に答える 1

2

技術的には、これは 1 つまたは複数のステートメントではなく、1 つの式ですが、区別はさほど重要ではありません。

Good old C makes only limited promises about what order expressions like this will be evaluated in. In your example, the order doesn't matter. But consider this expression:

a[i++] = i

If i was 1 before evaluating this expression, should a[1] now equal 1 or 2? As I understand the C specification, the behavior of this expression is undefined, meaning that what you get depends on which compiler you use.


Thanks to @mizo for a readable reference on sequence points, and to @ChrisDodd for pointing out that if you're making simple independent assignments that are separated by the comma operator, C and C++ do fully specify a left-to-right evaluation order.

于 2012-11-13T00:12:35.250 に答える