Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra commas in arrays

Tags:

d

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,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,];    
}
like image 255
Arlen Avatar asked Apr 14 '11 04:04

Arlen


2 Answers

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

like image 165
user541686 Avatar answered Sep 30 '22 23:09

user541686


It's allowed in many languages to allow code formatting like:

string[3] arr = [
    "Some long String",
    "And another",
    "etc, etc, etc",
    ];

without having to omit the comma from the last value.

Java permits such an array initializer too.

like image 27
Lawrence Dol Avatar answered Sep 30 '22 22:09

Lawrence Dol