foreach syntax
Most modern languages use very similar syntax inspired by C; but the features added since C are really non-standard! The “for-each” syntax annoys me particularly. I mean none of these is significantly better/worse than the others, but I program in all these languages (apart from C#) on a regular basis and I always have to think when typing in the line in order not to get the wrong syntax.
| PHP | foreach (list as element) |
| Perl | foreach my element (list) |
| Java | for (element : list) |
| Javascript | for (var element in list) |
| C# | foreach (element in list) |
For what it’s worth, I think “foreach” is nicer than “for” as it reads more like a sentence (the word “for” really makes no sense at all in that context); and about “in” vs. colon I’ve got no preference really.
BTW, there’s `for each … in` since JS 1.6, see:
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for_each…in :)
You can add Python (where I am doing most of my work nowadays) with yet another slightly different syntax:
for element in list:
Btw: Python does not even know a C-style for loop, you can only iterate over lists there. An C-style for loop would be
for i in range(n):
Concerning the semantics of for vs. foreach: I believe in mathematics, when talking about sets you say “for all x in Y”, this even has a distinct sign (∀) – so “for” really is short for “for all”, not “for each” for people who have a math background.