On Thu, 09 Aug 2012 19:25:47 +0200, egslava <egsl...@gmail.com> wrote:

Hello! Sorry for my English.

I read manual about "immutable" and "const" keyword:
http://dlang.org/const3.html

And tried to build my program:
http://dpaste.dzfl.pl/f803ae94

If I will change "immutable" to "const" output will not changed.
But why? Why output is look like this?

I would understand the output like this:
10
10
7FFF7E68AEB0
7FFF7E68AEB0

In this case, I would think - we just ignoring all assign operators.

I would understand the output like this:
10
20
7FFF7E68AEB0
FFFFFFFFFFFFF

In this case, I would think - we just one more time located memory and copied value of variable.

But why the output does look like this? How does this construction work? Why memory addresses are same, assign is working, but value of immutable variable doesn't change?

I would even think, that in compile-time compiler changes
writeln(x) to writeln(10), but why we can dereference "x"?

The compiler has optimized the call to writeln(x), by assuming x will never
change (which is reasonable). Now, since x is a variable, not a manifest
constant (which you would get by writing enum x = 10;, for instance), it
has a memory location, so you can ask for its address.

The reason you get the same value for both y and &x, is that they point to
the same location, and the first writeln call simply ignores the value
stored there.

Finally, the reason this does not behave like you'd expect is because
casts are a deliberate hole in the type system, and casting away immutability leads to undefined behavior (in this case, changing the value of the immutable
variable does not change the value where that variable is used).

--
Simen

Reply via email to