Debian Codegraph @

llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/misplaced-widening-cast.rst

raw
1 .. title:: clang-tidy - bugprone-misplaced-widening-cast
2
3 bugprone-misplaced-widening-cast
4 ================================
5
6 This check will warn when there is a cast of a calculation result to a bigger
7 type. If the intention of the cast is to avoid loss of precision then the cast
8 is misplaced, and there can be loss of precision. Otherwise the cast is
9 ineffective.
10
11 Example code:
12
13 .. code-block:: c++
14
15 long f(int x) {
16 return (long)(x * 1000);
17 }
18
19 The result ``x * 1000`` is first calculated using ``int`` precision. If the
20 result exceeds ``int`` precision there is loss of precision. Then the result is
21 casted to ``long``.
22
23 If there is no loss of precision then the cast can be removed or you can
24 explicitly cast to ``int`` instead.
25
26 If you want to avoid loss of precision then put the cast in a proper location,
27 for instance:
28
29 .. code-block:: c++
30
31 long f(int x) {
32 return (long)x * 1000;
33 }
34
35 Implicit casts
36 --------------
37
38 Forgetting to place the cast at all is at least as dangerous and at least as
39 common as misplacing it. If :option:`CheckImplicitCasts` is enabled the check
40 also detects these cases, for instance:
41
42 .. code-block:: c++
43
44 long f(int x) {
45 return x * 1000;
46 }
47
48 Floating point
49 --------------
50
51 Currently warnings are only written for integer conversion. No warning is
52 written for this code:
53
54 .. code-block:: c++
55
56 double f(float x) {
57 return (double)(x * 10.0f);
58 }
59
60 Options
61 -------
62
63 .. option:: CheckImplicitCasts
64
65 If `true`, enables detection of implicit casts. Default is `false`.