Home > Backend Development > C++ > body text

How to Initialize C Arrays of Objects in an Embedded Environment?

Barbara Streisand
Release: 2024-11-06 17:21:03
Original
987 people have browsed it

How to Initialize C   Arrays of Objects in an Embedded Environment?

Constructor Initialization for C Arrays

Initializing arrays of objects in C can be challenging due to the lack of an array initializer syntax similar to that available for non-array objects.

Consider the following non-array example:

struct Foo {
    Foo(int x) { /* ... */ }
};

struct Bar {
    Foo foo;

    Bar() : foo(4) {}
};
Copy after login

In this example, the Bar constructor initializes the foo member object using the initializer syntax : foo(4).

However, for arrays, the situation is different. The following syntax is incorrect:

struct Foo {
    Foo(int x) { /* ... */ }
};

struct Baz {
    Foo foo[3];

    // ??? I know the following syntax is wrong, but what's correct?
    Baz() : foo[0](4), foo[1](5), foo[2](6) {}
};
Copy after login

Solution

Unfortunately, in the context of C 98 (which seems to be the case here as suggested by the embedded processor limitation), there is no way to achieve array member initialization using constructor initializers. The workaround is to provide a default constructor for array members and perform any necessary initialization inside the constructor.

For instance:

struct Foo {
    Foo() : value(0) { /* ... */ }  // Default constructor with a default value

    Foo(int x) { /* ... */ }
};

struct Baz {
    Foo foo[3];

    Baz() {
        foo[0] = Foo(4);
        foo[1] = Foo(5);
        foo[2] = Foo(6);
    }
};
Copy after login

While this approach is not as elegant as direct initialization, it allows for creating and initializing arrays of objects without resorting to external initialization methods or STL constructs that may not be available in embedded environments.

The above is the detailed content of How to Initialize C Arrays of Objects in an Embedded Environment?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!