1

Some C-like languages allow multiple statements in the update part of a for statement, e.g.

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

Java explicitly defines the order for such statements in JLS 14.14.1.2 and 15.8.3 of ECMA-334 (C#) says "the expressions of the for-iterator, if any, are evaluated in sequence" which I'm reading as left-to-right.

What languages, if any, allow multiple statements in the update part of a for loop but either don't define an ordering for such statements or use an order other than left to right?

edit: removed the C tag since that started a sequence point discussion and there's plenty of that already.

Community
  • 1
  • 1
everial
  • 302
  • 1
  • 10
  • In C that is called the [comma operator](http://en.wikipedia.org/wiki/Comma_operator) and is not exclusive to `for` loops. – makes Nov 13 '12 at 00:10

1 Answers1

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.

Jamey Sharp
  • 8,363
  • 2
  • 29
  • 42
  • 1
    Understanding how [sequence points](http://en.wikipedia.org/wiki/Sequence_point) work is key. – makes Nov 13 '12 at 00:16