const?? When and why? This is ugly!
grauzone
none at example.net
Sun Mar 8 10:46:59 PDT 2009
Walter Bright wrote:
> Derek Parnell wrote:
>> import std.stdio;
>> void main()
>> {
>> int [] a = new int [1];
>>
>> a [0] = 1;
>>
>> invariant (int) [] b = cast (invariant (int) []) a;
>>
>> writef ("a=%s b=%s\n", a [0], b[0]);
>> a [0] += b [0];
>> writef ("a=%s b=%s\n", a [0], b[0]);
>> a [0] += b [0];
>> writef ("a=%s b=%s\n", a [0], b[0]);
>> }
>> The problem is that we have declared 'b' as invariant, but the
>> program is
>> allowed to change it. That is the issue.
>>
>
> The following also compiles:
>
> char c;
> int* p = cast(int*)&c;
> *p = 5;
>
> and is clearly buggy code. Whenever you use a cast, the onus is on the
> programmer to know what they are doing. The cast is an escape from the
> typing system.
Sometimes a cast can break a program, sometimes a cast is absolutely
harmless:
int w, h;
double ratio = (cast(double)w) / h;
Sure you don't want to introduce something like dangerous_cast() if a
cast dangerous, because it e.g. reinterprets raw memory bytes, or
aliases immutable memory to mutable memory?
More information about the Digitalmars-d
mailing list