access foreach index counter for Iterate n times

user1234 user1234 at 12.de
Sat May 21 15:21:09 UTC 2022


On Saturday, 21 May 2022 at 15:06:31 UTC, mw wrote:
> On Saturday, 21 May 2022 at 11:59:42 UTC, Adam D Ruppe wrote:
>> On Saturday, 21 May 2022 at 03:01:39 UTC, mw wrote:
>>> Yes! let's call it "loop counter"
>>
>> It isn't a loop counter. It is an index back into the original 
>> source. Consider:
>>
>> foreach(INDEX, dchar character; "“”")
>>    writeln(INDEX); // 0 then 3
>
> Wow, thus surprised me again!
>
> 1) First, why not 0 then 4? Since dchar is 32 bits.
>
> 2) Second, compare:
>
> import std;
> void main()
> {
>     dstring ds = "“”";
>     writeln(ds.length);
>     foreach(INDEX, dchar character; ds)
>       writeln(INDEX, character); // 0 then
> }
>
> Output:
> 2
> 0“
> 1”
>
> Explanations?

Adam D Ruppe expamples implies auto (hidden) decoding, which is a 
special case, so it reads 3 bytes to decode the the 1st glyph. 
The word "counter" is actually correct if the foreach'd aggregate 
is truely capable of random accesses. That is the case for your 
second version, that iterated over a dstring.

>
> If it's "loop counter", isn't the behavior more consistent?




More information about the Digitalmars-d mailing list