Home Item 28 - Designated Initializer (English)
Post
Cancel

Item 28 - Designated Initializer (English)

Designated Initializer

In C++20, the designated initializer is a syntax that allows us to explicitly specify how each member of a structure or union is initialized when using an initializer list. This syntax originates from the C language and is supported in C++20. With designated initializers, you can specify particular members to initialize within the structure or union by name, rather than initializing them in the order they are defined.

Basic Syntax:

1
2
3
4
5
6
StructType instance = {
    .member1 = value1,
    .member2 = value2,
    // ...other members
};

Here, .member specifies the member of the structure or union to initialize, and value is the value with which to initialize that member.

code

1
2
3
4
5
6
struct Point {
    int x;
    int y;
    int z;
};

We can use designated initializer to initialize its members in any order:

1
2
3
4
5
Point p = {
    .x = 1,
    .z = 3,
    .y = 2
};

If you have experience with Python, you might find this syntax familiar.

We can initialize members in any order defined, so there is no need to be careful every time we initialize, to see the order of structure members, because careless causes unnecessary bug

Benefits

  1. Clarity: Makes the code clearer by explicitly showing how each member is initialized.
  2. Flexibility: Allows initialization of members in any order, rather than the order defined in the structure.
  3. Safety: Helps prevent issues caused by incorrect member initialization order.

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍