5

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?

vsoftco
  • 55,410
  • 12
  • 139
  • 252
daljinder singh
  • 177
  • 1
  • 9
  • 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. – François Andrieux May 17 '17 at 17:51

1 Answers1

5

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.

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • 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`). – Jesper Juhl May 17 '17 at 18:08
  • This is not only with new syntax. `int a[] = {ld};` was valid C++03 but became invalid in C++11. –  May 17 '17 at 18:18
  • @hvd I think that's also now considered list initialization, although cannot bet on it. – vsoftco May 17 '17 at 18:21