Home >Backend Development >C++ >How to Initialize C Arrays of Objects in an Embedded Environment?

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-06 17:21:031093browse

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) {}
};

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) {}
};

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);
    }
};

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!

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