xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/modernize/use-designated-initializers.rst (revision 31b84d459cea6bde7f8cb232e70ffb0cf8e5d1ed)
1.. title:: clang-tidy - modernize-use-designated-initializers
2
3modernize-use-designated-initializers
4=====================================
5
6Finds initializer lists for aggregate types which could be written as designated
7initializers instead.
8
9With plain initializer lists, it is very easy to introduce bugs when adding new
10fields in the middle of a struct or class type. The same confusion might arise
11when changing the order of fields.
12
13C++20 supports the designated initializer syntax for aggregate types. By
14applying it, we can always be sure that aggregates are constructed correctly,
15because every variable being initialized is referenced by its name.
16
17Example:
18
19.. code-block::
20
21    struct S { int i, j; };
22
23is an aggregate type that should be initialized as
24
25.. code-block::
26
27    S s{.i = 1, .j = 2};
28
29instead of
30
31.. code-block::
32
33    S s{1, 2};
34
35which could easily become an issue when ``i`` and ``j`` are swapped in the
36declaration of ``S``.
37
38Even when compiling in a language version older than C++20, depending on your
39compiler, designated initializers are potentially supported. Therefore, the
40check is by default restricted to C99/C++20 and above. Check out the options
41``-Wc99-designator`` to get support for mixed designators in initializer list in
42C and ``-Wc++20-designator`` for support of designated initializers in older C++
43language modes.
44
45Options
46-------
47
48.. option::  IgnoreMacros
49
50  The value `false` specifies that components of initializer lists expanded from
51  macros are not checked. The default value is `true`.
52
53.. option:: IgnoreSingleElementAggregates
54
55    The value `false` specifies that even initializers for aggregate types with
56    only a single element should be checked. The default value is `true`.
57
58.. option:: RestrictToPODTypes
59
60    The value `true` specifies that only Plain Old Data (POD) types shall be
61    checked. This makes the check applicable to even older C++ standards. The
62    default value is `false`.
63
64.. option:: StrictCStandardCompliance
65
66   When set to `false`, the check will not restrict itself to C99 and above.
67   The default value is `true`.
68
69.. option:: StrictCppStandardCompliance
70
71   When set to `false`, the check will not restrict itself to C++20 and above.
72   The default value is `true`.
73