• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. title:: clang-tidy - cppcoreguidelines-narrowing-conversions
2
3cppcoreguidelines-narrowing-conversions
4=======================================
5
6Checks for silent narrowing conversions, e.g: ``int i = 0; i += 0.1;``. While
7the issue is obvious in this former example, it might not be so in the
8following: ``void MyClass::f(double d) { int_member_ += d; }``.
9
10This rule is part of the "Expressions and statements" profile of the C++ Core
11Guidelines, corresponding to rule ES.46. See
12
13https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es46-avoid-lossy-narrowing-truncating-arithmetic-conversions.
14
15We enforce only part of the guideline, more specifically, we flag narrowing conversions from:
16 - an integer to a narrower integer (e.g. ``char`` to ``unsigned char``),
17 - an integer to a narrower floating-point (e.g. ``uint64_t`` to ``float``),
18 - a floating-point to an integer (e.g. ``double`` to ``int``),
19 - a floating-point to a narrower floating-point (e.g. ``double`` to ``float``)
20   if WarnOnFloatingPointNarrowingConversion Option is set.
21
22This check will flag:
23 - All narrowing conversions that are not marked by an explicit cast (c-style or
24   ``static_cast``). For example: ``int i = 0; i += 0.1;``,
25   ``void f(int); f(0.1);``,
26 - All applications of binary operators with a narrowing conversions.
27   For example: ``int i; i+= 0.1;``.
28
29
30Options
31-------
32
33.. option:: WarnOnFloatingPointNarrowingConversion
34
35    When `true`, the check will warn on narrowing floating point conversion
36    (e.g. ``double`` to ``float``). `true` by default.
37
38.. option:: PedanticMode
39
40    When `true`, the check will warn on assigning a floating point constant
41    to an integer value even if the floating point value is exactly
42    representable in the destination type (e.g. ``int i = 1.0;``).
43    `false` by default.
44
45FAQ
46---
47
48 - What does "narrowing conversion from 'int' to 'float'" mean?
49
50An IEEE754 Floating Point number can represent all integer values in the range
51[-2^PrecisionBits, 2^PrecisionBits] where PrecisionBits is the number of bits in
52the mantissa.
53
54For ``float`` this would be [-2^23, 2^23], where ``int`` can represent values in
55the range [-2^31, 2^31-1].
56
57 - What does "implementation-defined" mean?
58
59You may have encountered messages like "narrowing conversion from 'unsigned int'
60to signed type 'int' is implementation-defined".
61The C/C++ standard does not mandate two’s complement for signed integers, and so
62the compiler is free to define what the semantics are for converting an unsigned
63integer to signed integer. Clang's implementation uses the two’s complement
64format.
65