Skip to content

Commit a9034d0

Browse files
authored
[clang-tidy][docs] improve documentation on cppcoreguidelines-narrowing-conversions (#111510) (#118209)
This PR improves the docs for this check to include an example of hidden narrowing conversions from the integer promotion rules in arithmetic.
1 parent 4eba40c commit a9034d0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,40 @@ This check will flag:
2727
- All applications of binary operators with a narrowing conversions.
2828
For example: ``int i; i+= 0.1;``.
2929

30+
Arithmetic with smaller integer types than ``int`` trigger implicit conversions,
31+
as explained under `"Integral Promotion" on cppreference.com
32+
<https://en.cppreference.com/w/cpp/language/implicit_conversion>`_.
33+
This check diagnoses more instances of narrowing than the compiler warning
34+
`-Wconversion` does. The example below demonstrates this behavior.
35+
36+
.. code-block:: c++
37+
38+
// The following function definition demonstrates usage of arithmetic with
39+
// integer types smaller than `int` and how the narrowing conversion happens
40+
// implicitly.
41+
void computation(short argument1, short argument2) {
42+
// Arithmetic written by humans:
43+
short result = argument1 + argument2;
44+
// Arithmetic actually performed by C++:
45+
short result = static_cast<short>(static_cast<int>(argument1) + static_cast<int>(argument2));
46+
}
47+
48+
void recommended_resolution(short argument1, short argument2) {
49+
short result = argument1 + argument2;
50+
// ^ warning: narrowing conversion from 'int' to signed type 'short' is implementation-defined
51+
52+
// The cppcoreguidelines recommend to resolve this issue by using the GSL
53+
// in one of two ways. Either by a cast that throws if a loss of precision
54+
// would occur.
55+
short result = gsl::narrow<short>(argument1 + argument2);
56+
// Or it can be resolved without checking the result risking invalid results.
57+
short result = gsl::narrow_cast<short>(argument1 + argument2);
58+
59+
// A classical `static_cast` will silence the warning as well if the GSL
60+
// is not available.
61+
short result = static_cast<short>(argument1 + argument2);
62+
}
63+
3064

3165
Options
3266
-------

0 commit comments

Comments
 (0)