Home > Backend Development > C++ > body text

How to Initialize Arrays in Member Initializer Lists in C ?

Patricia Arquette
Release: 2024-11-13 11:52:02
Original
631 people have browsed it

How to Initialize Arrays in Member Initializer Lists in C  ?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template