• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. title:: clang-tidy - bugprone-suspicious-semicolon
2
3bugprone-suspicious-semicolon
4=============================
5
6Finds most instances of stray semicolons that unexpectedly alter the meaning of
7the code. More specifically, it looks for ``if``, ``while``, ``for`` and
8``for-range`` statements whose body is a single semicolon, and then analyzes the
9context of the code (e.g. indentation) in an attempt to determine whether that
10is intentional.
11
12.. code-block:: c++
13
14    if (x < y);
15    {
16      x++;
17    }
18
19Here the body of the ``if`` statement consists of only the semicolon at the end
20of the first line, and `x` will be incremented regardless of the condition.
21
22
23.. code-block:: c++
24
25    while ((line = readLine(file)) != NULL);
26      processLine(line);
27
28As a result of this code, `processLine()` will only be called once, when the
29``while`` loop with the empty body exits with `line == NULL`. The indentation of
30the code indicates the intention of the programmer.
31
32
33.. code-block:: c++
34
35    if (x >= y);
36    x -= y;
37
38While the indentation does not imply any nesting, there is simply no valid
39reason to have an `if` statement with an empty body (but it can make sense for
40a loop). So this check issues a warning for the code above.
41
42To solve the issue remove the stray semicolon or in case the empty body is
43intentional, reflect this using code indentation or put the semicolon in a new
44line. For example:
45
46.. code-block:: c++
47
48    while (readWhitespace());
49      Token t = readNextToken();
50
51Here the second line is indented in a way that suggests that it is meant to be
52the body of the `while` loop - whose body is in fact empty, because of the
53semicolon at the end of the first line.
54
55Either remove the indentation from the second line:
56
57.. code-block:: c++
58
59    while (readWhitespace());
60    Token t = readNextToken();
61
62... or move the semicolon from the end of the first line to a new line:
63
64.. code-block:: c++
65
66    while (readWhitespace())
67      ;
68
69      Token t = readNextToken();
70
71In this case the check will assume that you know what you are doing, and will
72not raise a warning.
73