Multi dimensional array question.

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Thu Jul 15 07:39:33 PDT 2010


On Wed, 14 Jul 2010 16:57:13 -0400, Heywood Floyd wrote:

> Lars T. Kyllingstad Wrote:
> 
> 
>> But then arrays would be different from all other types!  If you have
>> an array of 3 Ts, that is written T[3], regardless of what T is.  Now
>> consider these two cases:
>> 
>>    A. T is an int.  Then T[3] becomes int[3].
>> 
>>    B. T is an int[string].  Then T[3] becomes int[string][3].
>> 
>> In case A, the first element of the array is accessed like this:
>> 
>>    int[3] a;
>>    int firstA = a[0];
>> 
>> Since a is an array of int, firstA is of course an int.
>> 
>> But then, since b is an array of int[string], we have
>> 
>>    int[string][3] b;
>>    int[string] firstB = b[0];
>> 
>> If we again want to access element "foo" of the associative array which
>> is firstB, we write firstB["foo"].  And so we have the following three
>> ways to get to that element, which *must* be equivalent because that's
>> how the language is defined:
>> 
>>    // Using firstB as an intermediate step int[string] firstB = b[0];
>>    int x = firstB["foo"];
>> 
>>    // Drop the intermediate variable firstB int x = (b[0])["foo"];
>> 
>>    // Drop the redundant parentheses
>>    int x = b[0]["foo"];
>> 
>> So you see, it can't be any other way than the way it is. :)
>> 
>> -Lars
> 
> Thank you for the elaborate answer!
> 
> When you put it like that, it does make sense. But I'm sorry. I refuse.
> The reason I refuse is those examples are void of any higher semantic
> meaning. Once we add a semantic meaning, it simply becomes backwards:
> 
> int[MAX_WIDTH][MAX_HEIGHT] map2d;
> map2d[x][y] = 9; // Wrong!
> 
> At least in my head, this is cognitive dissonance. To me, the language
> acts as if it's low-level semantics outweighs my high-level semantics
> and I should correct my thinking for that. I refuse! Seems to me it
> could just as well work as:
> 
> int[string][3] b;
> int[3] firstB = b["foo"];
> int i = firstB[0];
> int j = (b["foo"])[0];
> int k = b["foo"][0];
> 
> But I feel like I'm the only one feeling this, so I'll just let it go
> and hope my dear C-style arrays stay in :)
> 
> BR
> /HF
> 
> PS. Never thought I'd find a reason to love C.. DS.


I do agree that, if possible, the language should match how most people 
think.  But in this case, it is impossible, because of templates.  How 
would the following example work with T = int[3], if arrays worked the 
way you want?

  struct MyArray(T)
  {
      T[] a;
  }

C doesn't have this issue, because it doesn't have templates.  And I'll 
have my templates over C-style array declarations any time, thank you. :)

-Lars


More information about the Digitalmars-d-learn mailing list