Cleverness of the compiler

Namespace rswhite4 at googlemail.com
Mon Nov 25 02:34:39 PST 2013


On Monday, 25 November 2013 at 03:13:48 UTC, Shammah Chancellor 
wrote:
> On 2013-11-25 00:08:50 +0000, Namespace said:
>
>> I love this feature, but I'm unsure how it works. Can someone 
>> explain me, how the compiler deduce that he should read 4 
>> bytes for each index (the 'at' function)? The type is void*, 
>> not int*.
>
> It doesn't work.  That code is buggy.  It's overwriting 
> previous elements with new ones.   Indexing a void* only moves 
> up by 1 byte.
>
> void main() {
>  pragma(msg, void.sizeof)
> 	Tarray arr;
> 	arr.push(42);
> 	int a;
> 	arr.at(0, &a);
> 	writeln(a, "::", arr.length, "::", arr.capacity);
> 	arr.push(23);
> 	arr.at(1, &a);
> 	writeln(a, "::", arr.length, "::", arr.capacity);
> 	arr.push(1337);
> 	arr.at(2, &a);
> 	writeln(a, "::", arr.length, "::", arr.capacity);
>  writeln(arr.capacity);
> 	arr.push(ushort.max); //Write a ushort to test.
> 	arr.at(3, &a); //Only works because we're on a little endian 
> platform
> 	writeln(a, "::", arr.length, "::", arr.capacity);
> 	arr.at(2, &a);
> 	writeln(a, "::", arr.length, "::", arr.capacity);
> }

Ok, that calms me down. Thought I had missed something.


More information about the Digitalmars-d-learn mailing list