Debian Codegraph @

clang-tools-extra/docs/clang-tidy/checks/bugprone/switch-missing-default-case.rst

raw
1 .. title:: clang-tidy - bugprone-switch-missing-default-case
2
3 bugprone-switch-missing-default-case
4 ====================================
5
6 Ensures that switch statements without default cases are flagged, focuses only
7 on covering cases with non-enums where the compiler may not issue warnings.
8
9 Switch statements without a default case can lead to unexpected
10 behavior and incomplete handling of all possible cases. When a switch statement
11 lacks a default case, if a value is encountered that does not match any of the
12 specified cases, the program will continue execution without any defined
13 behavior or handling.
14
15 This check helps identify switch statements that are missing a default case,
16 allowing developers to ensure that all possible cases are handled properly.
17 Adding a default case allows for graceful handling of unexpected or unmatched
18 values, reducing the risk of program errors and unexpected behavior.
19
20 Example:
21
22 .. code-block:: c++
23
24 // Example 1:
25 // warning: switching on non-enum value without default case may not cover all cases
26 switch (i) {
27 case 0:
28 break;
29 }
30
31 // Example 2:
32 enum E { eE1 };
33 E e = eE1;
34 switch (e) { // no-warning
35 case eE1:
36 break;
37 }
38
39 // Example 3:
40 int i = 0;
41 switch (i) { // no-warning
42 case 0:
43 break;
44 default:
45 break;
46 }
47
48 .. note::
49 Enum types are already covered by compiler warnings (comes under -Wswitch)
50 when a switch statement does not handle all enum values. This check focuses
51 on non-enum types where the compiler warnings may not be present.
52
53 .. seealso::
54 The `CppCoreGuideline ES.79 <https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-default>`_
55 provide guidelines on switch statements, including the recommendation to
56 always provide a default case.