Declaration and Initialization

Designated Initializers in C++

Learn C++20 designated initializers: name struct members in a brace list, follow the aggregate rules, avoid common compile errors, and compare with C99.

On this page
  1. Short answer
  2. Why name the members?
  3. Basic syntax
  4. Members you leave out
  5. The rules in C++20
  6. Compiling with C++20
  7. Designated initializers in C
  8. A practical example: an options struct
  9. Common mistakes
  10. Summary

Short answer

Designated initializers let you name each member you are setting inside a brace list, such as .x = 1. The compiler matches each value to the member with that name instead of by position. C++20 added this feature for aggregate types. C has had a broader version since C99.

Why name the members?

A positional brace list depends on the order of the members. When a struct has several members of the same type, a swapped value compiles without any warning:

struct Size {
    int width;
    int height;
};

Size s{600, 400};  // Which number is the width? Only the declaration tells you.

Naming the members removes the guesswork:

Size s{.width = 600, .height = 400};

If you later reorder the members, the compiler rejects designators that are out of order. A mistake like that shows up at compile time instead of silently giving the wrong values.

Basic syntax

struct Point {
    int x;
    int y;
    int z;
};

Point p{.x = 1, .z = 3};              // y is not named, so it becomes 0
Point q = {.x = 4, .y = 5, .z = 6};   // the = form works too

Each designator starts with a dot, followed by a member name and =. You can list only the members you care about, but the names must appear in the order the members are declared.

Members you leave out

A member you don’t name is initialized the same way as in ordinary aggregate initialization:

  • If the member has a default member initializer, that value is used.
  • Otherwise, a scalar member such as an int or a bool is set to zero or false.
  • Otherwise, a member of class type uses its default constructor.

This example uses a default member initializer:

#include <iostream>
#include <string>

struct ServerConfig {
    std::string host;
    int port = 80;          // default member initializer
    bool use_tls = false;
};

void start(const ServerConfig& config) {
    std::cout << config.host << ":" << config.port
              << (config.use_tls ? " (TLS)" : "") << "\n";
}

int main() {
    start(ServerConfig{.host = "localhost", .port = 8080});
    start(ServerConfig{.host = "example.com", .use_tls = true});
    return 0;
}

The output is:

localhost:8080
example.com:80 (TLS)

The second call leaves port out, so the default of 80 is used.

The rules in C++20

Designated initializers come with restrictions:

  • Aggregates only. The type must be an aggregate. A class that declares its own constructor, as described in c class constructor, is not an aggregate. Neither is a class with private or protected data members. Designators do not work with either.
  • Declaration order. Designators must follow the order in which the members are declared. You can skip members, but you cannot go back.
  • No mixing. A list cannot combine designated and positional values.
  • No nesting. You cannot name a member inside a member, such as .origin.x.
  • No array designators. Syntax such as [2] = 10 is not part of C++20.

The default access rules for struct and class members are covered in c struct vs class.

These lines show the errors you will see:

struct Point {
    int x;
    int y;
};

struct Rect {
    Point origin;
    int width;
};

Point a{.y = 2, .x = 1};   // error: designators are out of declaration order
Point b{1, .y = 2};        // error: positional and designated values are mixed
Rect r{.origin.x = 1};     // error: nested designators are not allowed in C++20

Compiling with C++20

Turn on C++20 explicitly:

  • GCC or Clang: -std=c++20, for example g++ -std=c++20 -Wall main.cpp
  • MSVC: /std:c++20

Older language modes may accept designated initializers as an extension, usually with a warning. Code that depends on that is not portable, so set the standard explicitly.

Designated initializers in C

C added designated initializers in C99. The C version is broader than the C++20 one:

#include <stdio.h>

struct point {
    int x;
    int y;
    int z;
};

int main(void) {
    struct point p = { .z = 3, .x = 1 };     /* out of order is allowed in C */
    int digits[10] = { [0] = 1, [9] = 9 };   /* array designators: C only */

    printf("%d %d %d\n", p.x, p.y, p.z);     /* prints: 1 0 3 */
    printf("%d %d\n", digits[0], digits[9]); /* prints: 1 9 */
    return 0;
}

C allows designators in any order and nested designators such as .origin.x. A later value for the same member also replaces an earlier one. C++20 allows none of these, and it has no array designators either.

A practical example: an options struct

Designated initializers work well for functions that take several optional settings:

#include <iostream>

struct RetryOptions {
    int max_attempts = 3;
    int delay_ms = 500;
    bool log_each_try = false;
};

void run_task(const RetryOptions& opts) {
    std::cout << "attempts=" << opts.max_attempts
              << " delay=" << opts.delay_ms << "ms"
              << " log=" << std::boolalpha << opts.log_each_try << "\n";
}

int main() {
    run_task({.log_each_try = true});                 // keep the other defaults
    run_task({.max_attempts = 5, .delay_ms = 100});   // override two defaults
    return 0;
}

The output is:

attempts=3 delay=500ms log=true
attempts=5 delay=100ms log=false

Each call says what its values mean. With plain positional arguments, the same information is harder to read.

Common mistakes

  • Misspelled member names. .prot = 80 fails to compile because no member has that name. The compiler catches the typo for you.
  • Forgetting the dot. Without the dot, the text is an ordinary expression, not a designator, and it does not name a member. Start each designator with a dot.
  • Changing the order. Reordering the names in a C++20 list fails, even when every name is present.
  • Using C-only syntax in C++. Array designators such as [0] = 1 and nested designators such as .origin.x do not compile in C++20. Set those values with a constructor or with assignments after the object is created.

Summary

Designated initializers make struct setup in C++20 easier to read, because each value is labeled with its member name. They work only on aggregates, the names must follow declaration order, and they cannot be mixed with positional values. Use -std=c++20, check the member names, and keep the designators in the order the members are declared.

Keep exploring

Guides from other topics

All topics →

Heap vs Stack Memory in C++

Learn how heap and stack memory differ in C++: how each is allocated, how long data lives, the speed and size trade-offs, and common mistakes, with examples.

Heap vs Stack 5 min read

Is C++ Better Than C?

C++ grew out of C and adds classes, templates, and a large standard library. Neither is better in every case. See how they differ and which suits your goals.

C++ vs C 4 min read

Should I Learn C++?

C++ is worth learning for games, embedded systems and performance-critical software, but it is demanding. Here is how to decide if it suits your goals.