Narrowing Conversion required while list initialization
Asked Answered
P

1

6

I read about narrowing conversion on the cpp reference website. I kind of understood it but what i am not getting is that why is the error present only in the first line.

    long double ld = 3.1415926536;
    int a{ld}, b = {ld}; // error: narrowing conversion required
    int c(ld), d = ld;   // ok: but value will be truncated

Why is the error only present in first line and not the second?

Patellate answered 17/5, 2017 at 17:44 Comment(1)
Keep in mind that uniform initialization is a newer concept. It was designed with the benefits of hindsight. Also keep in mind that it may not be trivial to change the behavior of long-standing mechanisms.Nylanylghau
I
6

Because the compiler is required to issue a diagnostic (in your case error) for narrowing only for list initialization (a.k.a. uniform initialization), introduced starting with C++11. For the pre-C++11 initialization without curly braces, there is no diagnostic required.

See the cppreference.com documentation for more details.

Also see this answer as to why the compiler is only required to issue a warning, not necessarily an error.

Incognizant answered 17/5, 2017 at 17:50 Comment(3)
Note that most compilers have options/flags you can enable that will cause them to also issue a diagnostic for narrowing conversions of the pre-C++11 form - if you so desire (for gcc this would be -Wnarrowing).Augur
This is not only with new syntax. int a[] = {ld}; was valid C++03 but became invalid in C++11.Gesticulate
@hvd I think that's also now considered list initialization, although cannot bet on it.Incognizant

© 2022 - 2024 — McMap. All rights reserved.