Is remove safe using foreach

Steven Schveighoffer schveiguy at gmail.com
Tue Dec 13 01:45:26 UTC 2022


On 12/12/22 7:54 PM, lili wrote:
> is foreach Syntactic sugar?, like for-range in C++, if it is, compiler 
> how implement
> 
> 

Yes it is syntax sugar. The lowering depends on what the item you're 
iterating is.

For an associative array `byKey`, it is converting the AA into a range 
of keys, and for a range, the compiler does:

foreach(k; aa.byKey)

=>

for(auto r = aa.byKey, auto k = r.front; !r.empty; r.popFront)

(note that the declaration isn't valid syntax in D, but the compiler can 
handle it)

How it's lowered isn't technically important, just know that it iterates 
over each key.

-Steve


More information about the Digitalmars-d-learn mailing list