Cleverness of the compiler

Shammah Chancellor anonymous at coward.com
Mon Nov 25 03:51:48 PST 2013


On 2013-11-25 10:34:39 +0000, Namespace said:

> 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.

Yeah.  You had me confused for a bit too.  :)  Couldn't figure out why 
Ushort.max was being re-read correctly.  I'm use to big-endian 
platforms.   It certainly would have been miraculous if the compiler 
knew what kind of elements you put in the array to be able to index to 
the right location.

-Shammah



More information about the Digitalmars-d-learn mailing list