Debian Codegraph @

clang-tools-extra/docs/clang-tidy/checks/bugprone/redundant-branch-condition.rst

raw
1 .. title:: clang-tidy - bugprone-redundant-branch-condition
2
3 bugprone-redundant-branch-condition
4 ===================================
5
6 Finds condition variables in nested ``if`` statements that were also checked in
7 the outer ``if`` statement and were not changed.
8
9 Simple example:
10
11 .. code-block:: c
12
13 bool onFire = isBurning();
14 if (onFire) {
15 if (onFire)
16 scream();
17 }
18
19 Here `onFire` is checked both in the outer ``if`` and the inner ``if`` statement
20 without a possible change between the two checks. The check warns for this code
21 and suggests removal of the second checking of variable `onFire`.
22
23 The checker also detects redundant condition checks if the condition variable
24 is an operand of a logical "and" (``&&``) or a logical "or" (``||``) operator:
25
26 .. code-block:: c
27
28 bool onFire = isBurning();
29 if (onFire) {
30 if (onFire && peopleInTheBuilding > 0)
31 scream();
32 }
33
34 .. code-block:: c
35
36 bool onFire = isBurning();
37 if (onFire) {
38 if (onFire || isCollapsing())
39 scream();
40 }
41
42 In the first case (logical "and") the suggested fix is to remove the redundant
43 condition variable and keep the other side of the ``&&``. In the second case
44 (logical "or") the whole ``if`` is removed similarly to the simple case on the
45 top.
46
47 The condition of the outer ``if`` statement may also be a logical "and" (``&&``)
48 expression:
49
50 .. code-block:: c
51
52 bool onFire = isBurning();
53 if (onFire && fireFighters < 10) {
54 if (someOtherCondition()) {
55 if (onFire)
56 scream();
57 }
58 }
59
60 The error is also detected if both the outer statement is a logical "and"
61 (``&&``) and the inner statement is a logical "and" (``&&``) or "or" (``||``).
62 The inner ``if`` statement does not have to be a direct descendant of the outer
63 one.
64
65 No error is detected if the condition variable may have been changed between the
66 two checks:
67
68 .. code-block:: c
69
70 bool onFire = isBurning();
71 if (onFire) {
72 tryToExtinguish(onFire);
73 if (onFire && peopleInTheBuilding > 0)
74 scream();
75 }
76
77 Every possible change is considered, thus if the condition variable is not
78 a local variable of the function, it is a volatile or it has an alias (pointer
79 or reference) then no warning is issued.
80
81 Known limitations
82 ^^^^^^^^^^^^^^^^^
83
84 The ``else`` branch is not checked currently for negated condition variable:
85
86 .. code-block:: c
87
88 bool onFire = isBurning();
89 if (onFire) {
90 scream();
91 } else {
92 if (!onFire) {
93 continueWork();
94 }
95 }
96
97 The checker currently only detects redundant checking of single condition
98 variables. More complex expressions are not checked:
99
100 .. code-block:: c
101
102 if (peopleInTheBuilding == 1) {
103 if (peopleInTheBuilding == 1) {
104 doSomething();
105 }
106 }