1

一些类 C 语言允许在语句的更新部分使用多个for语句,例如

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

Java 在 ECMA-334 (C#) 的JLS 14.14.1.2和 15.8.3 中明确定义了此类语句的顺序,说“for-iterator 的表达式(如果有的话)按顺序计算”,我将其解读为 left-向右。

哪些语言(如果有)允许在循环的更新部分中使用多个语句,for但要么不为此类语句定义顺序,要么使用从左到右以外的顺序?

编辑:删除了C标签,因为这开始了一个序列点讨论,而且已经 很多 了。

4

1 回答 1

2

Technically, that's a single expression, not one or more statements, though the distinction isn't super important.

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 回答