0

Language-lawyer-wise, which clause in the standard forbid below code:

int arr[] (10, 42); 

This would produce an array of 10 elements, each initalized to 42.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
user3791991
  • 129
  • 6
  • 4
    `int arr[10]; std::fill_n(arr, 10, 42);` – T.C. Jun 30 '14 at 23:00
  • 1
    The best you're going to get with actual initialization for a built-in array is probably `int arr_0[] = {MAGIC_REPEAT_MACRO(10, 42)};`. IIRC, `BOOST_PP_REPEAT` will allow that. The dupe really doesn't cover initialization in C++ AFAICT. – chris Jun 30 '14 at 23:02
  • Use `constexpr`, be happy :). Write a `constexpr` function that builds the array, call it from the initializer. – Ben Voigt Jun 30 '14 at 23:17
  • 2
    @user3791991: Why would you think that `(10, 42)` means "produce 10 elements, each initialized to 42"? No compiler would ever treat the first value as a count and the next value as an initializer. `std::vector` has a constructor that accepts such values, eg `std::vector arr(10, 42);`, but a plain ordinary array does not. – Remy Lebeau Jul 01 '14 at 00:43
  • @RemyLebeau, If the hypothetical cause is "lack of constructor" for those built-in types, then why would `int num(10);` work? That too appears like a constructor call. – user3791991 Jul 01 '14 at 02:22
  • @user3791991: That is value-initializing a single variable, not an array of values. The language produces for such syntax in value initialization. There is no such syntax for initializing an array, though. – Remy Lebeau Jul 01 '14 at 02:24
  • @RemyLebeau, I agreed that "non-class type" is the cause based after delved into Falias's answer. – user3791991 Jul 01 '14 at 02:46

2 Answers2

5

Language-lawyer wise, 8.5/17:

— If the initializer is a (non-parenthesized) braced-init-list, the object or reference is list-initialized (8.5.4).

— If the destination type is a reference type, see 8.5.3.

— If the destination type is an array of characters, an array of char16_t, an array of char32_t, or an array of wchar_t, and the initializer is a string literal, see 8.5.2.

— If the initializer is (), the object is value-initialized.

— Otherwise, if the destination type is an array, the program is ill-formed

A braced-init-list is { } where anything (or nothing) can be inside the brackets (for example, int arr[3] = {1,2,3}). With that in mind, none of the first 4 options are viable for int arr[] (10, 42);, leaving the last one indicating the program is ill-formed.

Falias
  • 636
  • 4
  • 7
0

8.5/14:

If the entity being initialized does not have class type, the expression-list in a parenthesized initializer shall be a single expression.

aschepler
  • 70,891
  • 9
  • 107
  • 161
  • I don't think that applies to `int arr[](expression);` which is not permitted anyway? – M.M Jul 01 '14 at 00:15