Skip to content

Commit b10c536

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

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

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

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

30+
Note that arithmetic with integer types may perform implicit conversions if the used integer types are smaller than ``int``.
31+
These rules are documented under `"Integral Promotion" on this cppreference.com <https://en.cppreference.com/w/cpp/language/implicit_conversion>`_
32+
page. The following example demonstrates this behavior and can be explored with `cppinsights.io <https://cppinsights.io/s/68553908>`_.
33+
34+
.. code-block:: c++
35+
36+
// The following function definition demonstrates usage of arithmetic with integer types smaller than `int`
37+
// and how the narrowing conversion happens implicitly.
38+
void computation(short argument1, short argument2) {
39+
// Arithmetic written by humans:
40+
short result = argument1 + argument2;
41+
// Arithmetic actually performed by C++:
42+
short result = static_cast<short>(static_cast<int>(argument1) + static_cast<int>(argument2));
43+
}
44+
45+
void recommended_with_gsl(short argument1, short argument2) {
46+
// This will throw an exception if the conversion will be lossy.
47+
short result = gsl::narrow<short>(argument1 + argument2);
48+
// This will just cast through and may yield incorrect results if the sum is not representable
49+
// by `short`.
50+
short result = gsl::narrow_cast<short>(argument1 + argument2);
51+
}
52+
3053

3154
Options
3255
-------

0 commit comments

Comments
 (0)