File tree Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Original file line number Diff line number Diff line change @@ -27,6 +27,29 @@ 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
+ 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
+
30
53
31
54
Options
32
55
-------
You can’t perform that action at this time.
0 commit comments