2

Consider the following code:

uint32_t foo(uint64_t x ) {
    auto y = uint32_t { x };
    return y;
}

It is considered a narrowing conversion the compiler feels compelled to warn me about (GCC 9) or even declare an error (clang 9): GodBolt.

My questions:

  1. Why is uint32_t { x } less explicit than static_cast<uint32_t>(x)?
  2. Why is this more severe with clang than with GCC, meriting an error?
0

3 Answers 3

3

Why is uint32_t { x } less explicit than static_cast<uint32_t>(x)?

It's not less explicit, it's just not allowed. Narrowing conversions are not allowed when doing direct or copy list initialization. When you do auto y = uint32_t { x }; you are direct-list-initializing y with a narrowing conversion. (Guaranteed Copy elision means there is no temporary here anymore)

Why is this more severe with clang than with GCC, meriting an error?

It's up the the implementers. Apparently clang wants to be more strict and issue a hard error, but both are fine. The standard only requires a diagnostic message be given, and a warning or error covers that.

2

Adding to @NathanOliver's answer - the warnings and errors go away if we construct the 32-bit integer like so:

uint32_t foo(uint64_t x ) {
    auto y = uint32_t(x);
    return y;
}

So, (x) and {x} here are not semantically equivalent (even if the same constructor would end up getting called, had it been a class). The no-narrowing guarantee in the standard apparently only applies to list-initialization, IIANM.

So, take this is a motivation for using curly-bracket initialization, if you want to be extra careful (or parentheses if you want to not be bothered.)

1

From https://en.cppreference.com/w/cpp/language/list_initialization:

Narrowing conversions

list-initialization limits the allowed implicit conversions by prohibiting the following:

...

-conversion from integer or unscoped enumeration type to integer type that cannot represent all values of the original, except where source is a constant expression whose value can be stored exactly in the target type

This sounds like clang is more conformant than gcc here (though beware that I'm not a language lawyer)*: the standard mandates that, if you use initalizer lists, you aren't in any danger of a narrowing conversion. This is a conscious design choice to remedy the rather promiscuous implicit conversion built into the language - and the admittedly clear way that you spell it out in your example is a collateral annoyance.

Edit: * and it didn't take long - it seems "not allowed" at cppreference translates to "implementer dependent" in the standard, as per NathanOliver's answer. That's what I get for not checking the source.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.