Home > Backend Development > C++ > How do I initialize constant arrays in C class initializers, both before and after C 11?

How do I initialize constant arrays in C class initializers, both before and after C 11?

Mary-Kate Olsen
Release: 2024-11-03 00:26:03
Original
605 people have browsed it

How do I initialize constant arrays in C   class initializers, both before and after C  11?

Initialization of Constant Arrays in Class Initializers in C

In C , when declaring arrays as constant members of a class, it can be challenging to initialize them within the class constructor due to the const qualifier. This article explores how to overcome this challenge in both pre- and post-C 11 contexts.

Pre-C 11:

Prior to C 11, initializing a const array in a class initializer was not directly possible using the traditional syntax. However, there is a workaround:

<code class="cpp">class a {
    const int *b;
    int b_size;
    
    // Constructor
    a(const int *b_array, int b_sz)
        : b(b_array), b_size(b_sz) {}
};

int main() {
    int b_array[] {2, 3};
    a a(b_array, sizeof(b_array) / sizeof(int));
    // Proceed with using class 'a'
}</code>
Copy after login

In this approach, instead of declaring the array as a direct member, it is declared as a pointer with a corresponding size member. The constructor is then used to allocate and initialize the pointer.

Post-C 11:

With the introduction of C 11, the initialization of const arrays in class initializers became more straightforward:

<code class="cpp">struct a {
    const int b[2];
    
    // Constructor
    a() : b{2, 3} {}
};</code>
Copy after login

In this syntax, the curly braces {} immediately following the class member declaration allow direct initialization of the const array within the constructor.

This change in C 11 simplifies the process of initializing const arrays in class initializers and provides a more concise and elegant way to define such classes.

The above is the detailed content of How do I initialize constant arrays in C class initializers, both before and after C 11?. 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