开发者

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 take开发者_JAVA技巧n the time to remove them.

even this compiles without errors:

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


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


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.


I'm 99% sure the single comma is by design. The 2nd, 3rd, etc.? IMHO, it's a bug in the design or implementation, but I don't know which.


Some months ago Walter committed this behavior into dmd. Before, a trailing comma was sometimes allowed and sometimes not, and if you're in dmd1 land, you're stuck with that.

Now, for dmd2, at least, a trailing comma should always be valid in an array literal, as well as in parameter lists, argument lists, and template argument lists.

The multiple trailing commas, however, is a bug in the implementation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜