@@ -27,6 +27,40 @@ This check will flag:
27
27
- All applications of binary operators with a narrowing conversions.
28
28
For example: ``int i; i+= 0.1; ``.
29
29
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
+
30
64
31
65
Options
32
66
-------
0 commit comments