Initializing a Const Array in a Class Initializer in C
In C , initializing a const array in the initializer list of a class can seem like a challenge due to the const keyword's restriction on in-function modification. However, this task is made possible with the introduction of C 11.
Previously, initializing a const array in the constructor body was not viable. Attempts to do so, as in the example code provided, resulted in errors. This was because const variables cannot be modified after initialization.
However, in C 11, a solution emerged: initializing the array within the constructor's initialization list. This approach allows us to specify the array's elements directly:
<code class="cpp">struct a { const int b[2]; // other stuff follows // Here's the constructor a() : b{2, 3} { // other constructor work } };</code>
In this example, the array b is initialized with the elements {2, 3}. This initialization ensures that the values of b remain constant throughout the object's lifetime.
It's important to note that different instances of the class a can have different values for b. However, the values for a specific instance remain constant once the constructor has executed. This behavior is what distinguishes these arrays from non-const arrays, which can be modified during the object's lifetime.
The above is the detailed content of How to Initialize a Const Array in a Class Initializer in C ?. For more information, please follow other related articles on the PHP Chinese website!