Home  >  Article  >  Backend Development  >  How to Initialize a Constant Array in a Class Initializer in C ?

How to Initialize a Constant Array in a Class Initializer in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-06 03:44:02326browse

How to Initialize a Constant Array in a Class Initializer in C  ?

Initializing a Constant Array in a Class Initializer in C

In C , initializing a constant array within a class's initializer list requires a slightly different approach than initializing other member variables. Let's explore the case where the constant array is meant to have instance-specific values.

Consider the following class:

<code class="cpp">class a {
public:
    const int b[2];
};</code>

To initialize b with specific values in the constructor initialization list, use the following syntax:

<code class="cpp">a::a() : b{2, 3} {
    // Other initialization stuff
}</code>

This approach relies on C 11's brace-enclosed initializer list syntax, which allows you to initialize a constant array within the class initializer. Here's an example:

<code class="cpp">struct a {
    const int b[2];

    // Constructor
    a() : b{2, 3} {}
};

int main() {
    a a;
}</code>

In this example, each instance of a will have a unique b array with the specified values. Note that this technique is not available in C 98 or earlier versions.

The above is the detailed content of How to Initialize a Constant Array in a Class Initializer in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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