Home > Article > Backend Development > Can You Use Constructor Initializers for Array Members in C ?
Constructor Initializers for Array Members in C
When working with arrays of objects in C , initializing them properly can be a challenging task. This article explores the limitations and workarounds for using constructor initializers for array members.
Non-Array Initialization
In the non-array example, the struct Bar can initialize its member foo using a constructor initializer:
struct Bar { Foo foo; Bar() : foo(4) {} };
Array Initialization
However, in the array example, the struct Baz cannot initialize its array member foo using the same syntax:
struct Baz { Foo foo[3]; // Incorrect Baz() : foo[0](4), foo[1](5), foo[2](6) {} };
Limitations
In C , arrays lack constructor support. As a result, array members are default initialized before any object initialization takes place. Therefore, it is not possible to initialize array members directly using constructor initializers.
Workaround
The provided solution in the question is to employ a workaround. Since STL constructs like std::vector are unavailable, a default constructor is created with an explicit init() method for post-construction initialization. This avoids the need for constructor initializers altogether.
Alternative Solution
Barry's response suggests a more recent approach. If the development environment supports C standards beyond C 98, a newer syntax is available:
struct Baz { Foo foo[3]{4, 5, 6}; };
This syntax allows the initialization of array members using curly braces, eliminating the need for a default constructor and explicit initialization method.
The above is the detailed content of Can You Use Constructor Initializers for Array Members in C ?. For more information, please follow other related articles on the PHP Chinese website!