0

The first two statements int a{ ld }; int b = { ld }; produce compiler errors C3297 and won't compile, but the 2nd definition/initialization with the parentheses works. Why?

#include<iostream>
using namespace std;
int main()
{
    
    long double ld = 3.1415926536;

    int a{ ld };
    int b = { ld };
    int c(ld);
    int d = ld;

    std::cin.get();
    std::cin.get();
    return 0;

}
Irelia
  • 3,407
  • 2
  • 10
  • 31
Spellbinder2050
  • 644
  • 3
  • 13
  • You just need to read up on C++ syntax. For primitive variable decleration/assignments – Irelia Apr 06 '21 at 00:43
  • 2
    What is the error `C3297`? Please copy-paste the full and complete error output into the question. – Some programmer dude Apr 06 '21 at 00:43
  • 1
    I also recommend that you split the line to two different definitions, so you know *which* of the definitions the error is about. – Some programmer dude Apr 06 '21 at 00:45
  • While I get that OP just wants an answer, one that the compiler is happy to provide: `error: type 'long double' cannot be narrowed to 'int' in initializer list`; I just wanted to note that this is a good thing. Variables `c` & `d` potentially lose data and you might not ever know. That's the kind of bug that bites you years down the line. – sweenish Apr 06 '21 at 00:45
  • https://stackoverflow.com/questions/31685132/why-doesnt-narrowing-conversion-used-with-curly-brace-delimited-initializer-cau gets you most of the way there. Compilers have changed the diagnostic message from a warning to an error, and it appears it was only a warning at first to allow developers a little leeway in getting their codebases converted. Also, https://en.cppreference.com/w/cpp/language/list_initialization , under 'Narrowing conversions' – sweenish Apr 06 '21 at 00:50
  • 1
    This first form is called [uniform initialization](https://isocpp.org/wiki/faq/cpp11-language#uniform-init), which does not allow narrowing conversions. Older forms of initialization syntax do. – Brian61354270 Apr 06 '21 at 00:51
  • The error is `"conversion from 'long double' to 'int' requires a narrowing conversion"` and is caused by `int d = ld;` I just didn't understand how () vs {} makes the behavior different, and I think my book expects me to wait 100 pages to explain it. – Spellbinder2050 Apr 06 '21 at 00:59

0 Answers0