[cfe-dev] [RFC] Is it narrowing that coverting unsigned int to const int &?

chuanqi.xcq via cfe-dev cfe-dev at lists.llvm.org
Tue Dec 15 17:53:01 PST 2020


Recently our collegues find that gcc and clang have different behavior on the following code:
```
int main() {
  uint32_t a = rand();
  uint32_t b = rand();
  std::tuple<std::vector<int>, uint32_t, int32_t> k{{}, 0, a - b};
  return std::get<1>(k);
}
```

gcc would warn the converting from `a-b` to the third arguments of the constructor with type const int32_t& is a narrowing convering. And the clang wouldn't emit any warnings. We want to figure it out which one is right (to diagnose or not).

From the standard documentation (N4849, 9.4.4 list initialization), I find the narrowing definition is:
```
A narrowing conversion is an implicit conversion
(7.1) — from a floating-point type to an integer type, or
(7.2) — from long double to double or float, or from double to float, except where the source is a constant
expression and the actual value after conversion is within the range of values that can be represented
(even if it cannot be represented exactly), or
(7.3) — from an integer type or unscoped enumeration type to a floating-point type, except where the source is
a constant expression and the actual value after conversion will fit into the target type and will produce
the original value when converted back to the original type, or
(7.4) — from an integer type or unscoped enumeration type to an integer type that cannot represent all the
values of the original type, except where the source is a constant expression whose value after integral
promotions will fit into the target type.
```

From the literal, I think that converting unsigned int to int is a narrowing while converting unsigned int to const int& is not narrowing. Since I think the reference type of an integer type is different from an integer type. 

So I want to ask that is it a narrowing that converting a unsigned int to const int&?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20201216/c4e108ed/attachment.html>


More information about the cfe-dev mailing list