Why D const is annoying

Mehrdad wfunction at hotmail.com
Wed May 2 01:06:47 PDT 2012


You can replace "signed integer overflow" with pretty much whatever 
'guarantee' in C that suits your fancy.
See below.


"Jonathan M Davis"  wrote in message 
news:mailman.207.1335944070.24740.digitalmars-d at puremagic.com...
> I don't follow.
Let's see if this is better.

> The D compiler guarantees that as long as you don't cast away const, const 
> will never be mutated.
The C compiler guarantees that as long as signed integers don't overflow, 
their results will be correct.

> If you _do_ cast away const and then mutate the variable, you are doing 
> something which is undefined.
If you _do_ overflow signed integers, their results will be undefined.

> As it is undefined behavior, _anything_ could happen if you do it, and the 
> compiler is free to assume that it will never happen.
As it is undefined behavior, the result could be _anything_ if you do it, 
and the compiler is free to assume that it will never happen.

> So, it effectively has a guarantee that a const variable will never be 
> mutated (save by another, mutable reference to the same data). It then 
> uses that guarantee for optimizations.
So, it effectively has a guarantee that a signed integer will never be 
overflown. It then uses that guarantee for optimizations.

> To make it 100% iron-clan, casting away const would have to be illegal, 
> but that would be unacceptable in a systems language - particularly when 
> you want to be able to call C functions which may not be properly 
> annotated.
To make it 100% iron-clan, signed overflow would have to be illegal, but 
that would be unacceptable in a systems language - particularly when you 
need to depend on system-dependent behavior.

> So instead, the compiler assumes that its guarantee holds in the case 
> where you cast away const, and is still able to use it for optimizations.
So instead, the compiler assumes that its guarantee holds in the case where 
overflow a signed integer, and is still able to use it for optimizations.

> C++ _does_ define what happens when you cast away const and mutate a 
> variable, so it guarantees that that behavior will be safe.
D _does_ define what happens when you overflow a signed integer, so it 
guarantees that that behavior will be safe.

> In so doing however, it is then unable to assume that casting away const 
> will not result in the variable being mutated and is therefore unable to 
> use const for much in the way of optimizations.
In so doing however, it is then unable to assume that a signed integer will 
never be overflown, and is therefore unable to use signed integer overflow 
for much in the way of optimizations.

- Jonathan M Davis
Mehrdad



More information about the Digitalmars-d mailing list