Skip to content

Commit f434566

Browse files
committed
[clang-tidy][docs] improve documentation on cppcoreguidelines-narrowing-conversions (#111510)
1 parent deed1b0 commit f434566

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,39 @@ 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 recommended way to resolve this issue with the GSL is one of two ways.
53+
// Either by a cast that throws if a loss of precision would occur.
54+
short result = gsl::narrow<short>(argument1 + argument2);
55+
// Or it can be resolved without checking the result.
56+
short result = gsl::narrow_cast<short>(argument1 + argument2);
57+
58+
// A classical `static_cast` will silence the warning as well if the GSL
59+
// is not available.
60+
short result = static_cast<short>(argument1 + argument2);
61+
}
62+
3063

3164
Options
3265
-------

0 commit comments

Comments
 (0)