Search code examples
d

Extra commas in arrays


void main(){    
  int[3] arr = [1, 2, 3,];    
}

Is the extra comma legal or is it not flagged as error because of a compiler bug? I have many mixins that generate arrays with the extra comma at the end. I would like to know if I should taken the time to remove them.

even this compiles without errors:

void main(){    
  int[3] arr = [1, 2, 3,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,];    
}

Solution

  • I believe it's legal in order to allow for templates (or even mixins) to work in a generic manner:

    template Foo(T) { }                       //What if Foo is empty like this?
    
    auto arr = [1, 2, Foo!(int), Foo!(long)];
    //         [1, 2, , ]
    

    It makes templates much easier to work with, so that you don't have to special-case against special outputs.

    A more realistic example:

    template Iota(size_t start, size_t end)  //All integers in range [start, end)
    {
        static if (start < end)
            alias TypeTuple!(start, Iota!(start + 1, end)) Iota;
        else
            alias TypeTuple!() Iota;
    }
    
    auto arr1 = [-10, Iota!(0, 3)];    // arr is now [-10, 0, 1, 2]
    auto arr2 = [-10, Iota!(a, b)];    // arr is now [-10, a .. b]
    

    Now what happens if a is equal to b? Then arr2 decays to [-10, ].