shorter foreach syntax - C++0x range-based for

Nick Treleaven nospam at example.net
Mon Nov 1 09:35:48 PDT 2010


On Mon, 01 Nov 2010 09:07:29 -0700, Jonathan M Davis wrote:

>> for (ref x : array)
>>   x *= 2;
>> 
>> Apart from being 4 chars shorter, I think it looks more natural using
>> the ':' instead of ';'. A lesser benefit is it allows reuse of the
>> 'for' keyword, making the 'foreach' keyword unnecessary.
>> 
>> Maybe this would be acceptable for D?
> 
> The current syntax has been around for quite a while, it's in TDPL, and
> making the change gives no significant improvement. Generally speaking,
> we're not really supposed to be making any major changes from what TDPL
> says without a really good reason. Saving a few characters is not a
> really good reason. foreach works just fine and is arguably clearer,
> since you know right away that you're dealing with a foreach loop rather
> than a for loop - and while similar, they _are_ semantically different.

OK.

> And I don't see why : would be better than ;. IIRC, Java uses one and C#
> uses the other and you have to remember which uses which when moving
> between the two.

Actually C# uses:

foreach (int x in array)

So D has its own unique syntax.

> And if you're looking to save typing, ; has the
> advantage that you don't have to use the shift key.

True, but still takes longer to type 'each' than press shift IMO. But 
readibility is perhaps more important than writing code.

> If D had chosen to just reuse for, that would have been fine, but it
> didn't, and I think that it's fine as it is. Changing foreach to for
> would not be a productive change in the least.

Fair enough.


More information about the Digitalmars-d mailing list