Initializer List for Array Members
The code snippet provided fails to compile due to an attempt to initialize an array in a member initializer list using the following syntax:
`
C() : arr({1,2,3}) <br>{}<br>// doesn't compile either<br>C() : arr{1,2,3} <br>{}`
This is because arrays in C 03 can only be initialized with the assignment operator, e.g. int arr[3] = {1,3,4}.
Solutions
Using a Struct:
The provided code can be fixed by using a struct to wrap the array and initializing it in the constructor, as follows:
`
int arr[3];<br> ArrayWrapper() : arr{1,2,3} {}<br>};<br>`
Using C 11 List Initialization:
In C 11, you can use list initialization to initialize arrays in a member initializer list:
`
int arr[3];<br> ArrayWrapper() : arr{1, 2, 3} {}<br>};<br>`
Standard Compliance:
The behavior is not explicitly addressed in the C 03 standard, but it is a corollary of the rule that aggregate initialization must use the assignment operator.
C 11 Clarification:
C 11 explicitly allows initializing arrays in member initializer lists using list initialization.
The above is the detailed content of How to Initialize Arrays in Member Initializer Lists in C ?. For more information, please follow other related articles on the PHP Chinese website!