About foreach loops

Jesse Phillips jessekphillips+D at gmail.com
Fri Jun 17 09:41:12 PDT 2011


Timon Gehr Wrote:

> Jesse Phillips wrote:
> > On Wed, 15 Jun 2011 16:40:24 -0400, bearophile wrote:
> >
> >> Isn't it undefined in D to modify a const?
> >
> > Yes, but unlike what every redditer is say, that doesn't mean the
> > compiler can do whatever it wants. It means you can't define its
> > behavior. Go ahead try.
> > [snip.]
> 
> How do "cannot do what it wants" and "the behavior cannot be defined" not
> contradict each other?

Because the compiler can't identify when it happens. Try making the compiler format your hard drive when you modify const. It can't do what it wants because it can't define what it will do!

> It may work as you would expect in some cases but not in others. "The compiler can
> do what it wants". The behavior will depend on what the compiler wants. The way
> out would be to just define the behavior of casting away const

Casting away const is defined. But once you do, the compiler can no longer identify when you are modifying its value. 

void main(){
    const a = 53;
    auto pa = &a;
    auto pb = cast(int*) pa;
    assert(*pb == *pa); // Always true, all implementations
}

> and mutating the
> memory to do the expected thing in case it is not typed as immutable somewhere in
> the program.

This is not possible. You don't know where the variable resides at compile time. The compiler doesn't know where in memory the values are stored and it isn't allowed to add code which checks where the variable is stored. This means if the variable is in modifiable memory then when you modify it, it will do exactly as you expect, even if it comes from an immutable declaration.

Your examples are flawed, declaring a variable with const is equivalent to declaring it immutable, the compiler is allowed to place it in read only memory (or at least that is what most people expect, I don't really know if the spec says anything on it).

void main(){
    int a = 53;
    const int* pa = &a;
    auto pb = cast(int*) pa;
    assert(*pb == *pa);
    *pb = 3;
    assert(*pb == *pa);
}

This will always be true on every implementation.


More information about the Digitalmars-d mailing list