xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/init-variables.rst (revision 0f1f1d45c9f77bf5d8e5dce32551b7c78772b8a6)
1.. title:: clang-tidy - cppcoreguidelines-init-variables
2
3cppcoreguidelines-init-variables
4================================
5
6Checks whether there are local variables that are declared without an initial
7value. These may lead to unexpected behavior if there is a code path that reads
8the variable before assigning to it.
9
10This rule is part of the `Type safety (Type.5)
11<https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Pro-type-init>`_
12profile and `ES.20 <https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-always>`_
13from the C++ Core Guidelines.
14
15Only integers, booleans, floats, doubles and pointers are checked. The fix
16option initializes all detected values with the value of zero. An exception is
17float and double types, which are initialized to NaN.
18
19As an example a function that looks like this:
20
21.. code-block:: c++
22
23   void function() {
24     int x;
25     char *txt;
26     double d;
27
28     // Rest of the function.
29   }
30
31Would be rewritten to look like this:
32
33.. code-block:: c++
34
35   #include <math.h>
36
37   void function() {
38     int x = 0;
39     char *txt = nullptr;
40     double d = NAN;
41
42     // Rest of the function.
43   }
44
45It warns for the uninitialized enum case, but without a FixIt:
46
47.. code-block:: c++
48
49   enum A {A1, A2, A3};
50   enum A_c : char { A_c1, A_c2, A_c3 };
51   enum class B { B1, B2, B3 };
52   enum class B_i : int { B_i1, B_i2, B_i3 };
53   void function() {
54     A a;     // Warning: variable 'a' is not initialized
55     A_c a_c; // Warning: variable 'a_c' is not initialized
56     B b;     // Warning: variable 'b' is not initialized
57     B_i b_i; // Warning: variable 'b_i' is not initialized
58   }
59
60Options
61-------
62
63.. option:: IncludeStyle
64
65   A string specifying which include-style is used, `llvm` or `google`. Default
66   is `llvm`.
67
68.. option:: MathHeader
69
70   A string specifying the header to include to get the definition of `NAN`.
71   Default is `<math.h>`.
72