85 lines · plain
1.. title:: clang-tidy - bugprone-invalid-enum-default-initialization2 3bugprone-invalid-enum-default-initialization4============================================5 6Detects default initialization (to 0) of variables with ``enum`` type where7the enum has no enumerator with value of 0.8 9In C++ a default initialization is performed if a variable is initialized with10initializer list or in other implicit ways, and no value is specified at the11initialization. In such cases the value 0 is used for the initialization.12This also applies to enumerations even if it does not have an enumerator with13value 0. In this way a variable with the ``enum`` type may contain initially an14invalid value (if the program expects that it contains only the listed15enumerator values).16 17The check emits a warning only if an ``enum`` variable is default-initialized18(contrary to not initialized) and the ``enum`` does not have an enumerator with19value of 0. The type can be a scoped or non-scoped ``enum``. Unions are not20handled by the check (if it contains a member of enumeration type).21 22Note that the ``enum`` ``std::errc`` is always ignored because it is expected23to be default initialized, despite not defining an enumerator with the value 0.24 25.. code-block:: c++26 27 enum class Enum1: int {28 A = 1,29 B30 };31 32 enum class Enum0: int {33 A = 0,34 B35 };36 37 void f() {38 Enum1 X1{}; // warn: 'X1' is initialized to 039 Enum1 X2 = Enum1(); // warn: 'X2' is initialized to 040 Enum1 X3; // no warning: 'X3' is not initialized41 Enum0 X4{}; // no warning: type has an enumerator with value of 042 }43 44 struct S1 {45 Enum1 A;46 S(): A() {} // warn: 'A' is initialized to 047 };48 49 struct S2 {50 int A;51 Enum1 B;52 };53 54 S2 VarS2{}; // warn: member 'B' is initialized to 055 56The check applies to initialization of arrays or structures with initialization57lists in C code too. In these cases elements not specified in the list (and have58enum type) are set to 0.59 60.. code-block:: c61 62 enum Enum1 {63 Enum1_A = 1,64 Enum1_B65 };66 struct Struct1 {67 int a;68 enum Enum1 b;69 };70 71 enum Enum1 Array1[2] = {Enum1_A}; // warn: omitted elements are initialized to 072 enum Enum1 Array2[2][2] = {{Enum1_A}, {Enum1_A}}; // warn: last element of both nested arrays is initialized to 073 enum Enum1 Array3[2][2] = {{Enum1_A, Enum1_A}}; // warn: elements of second array are initialized to 074 75 struct Struct1 S1 = {1}; // warn: element 'b' is initialized to 076 77 78Options79-------80 81.. option:: IgnoredEnums82 83 Semicolon-separated list of regexes specifying enums for which this check won't be84 enforced. Default is `::std::errc`.85