Const foreach
Jonathan M Davis
jmdavisProg at gmx.com
Sun Nov 21 18:44:34 PST 2010
On Sunday 21 November 2010 18:37:01 bearophile wrote:
> Jonathan M Davis:
> > Actually, const is pointless in your example, since you're dealing with a
> > value type.
>
> A const value time is meaningful, it means that you are saying the D
> compiler that you don't want to modify it. Generally it's good to stick a
> const/immutable even when you use values inside your functions.
True. But it's really only to help the compiler optimize better and perhaps to
stop yourself from accidentally mutating it if you don't want it to happen. If
the compiler's good enough, it shouldn't matter at all.
> > And unfortunately, I don't
> > think that it works to use const ref in a foreach (I've never gotten it
> > work anyway)
>
> I think it works (it has the same problems of the const alone, there is no
> type inference):
>
> void main() {
> int[3] array;
> foreach (ref const(int) x; array) {}
> }
It never occurred to me to use ref const(T). I tried const ref T, and that
didn't worked (or maybe I only tried const ref - I don't recall). In any case,
I've never figured out how to get const ref to work for foreach, so if what you
give there works, that's great.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list