I am working through a C++ book, to teach myself. The book I am working through Talks about narrowing through type conversions. It explains how a double can be narrowed to an int, and says "So what should you do if you think that a conversion might lead to a bad value? Use {} initializers to avoid accidents." It then gives a very limited example code and it has little context:
double x{ 2.7 }; // OK
int y(x); //error:double -> int might narrow
I tried running some code so I could see how it works, but my results were not what I expected:
double test {1.2};
cout << "First Line test = " << test << '\n';
test = 3 / 2;
cout << "Test = " << test << '\n';
From what I read, I was under the impression if I initialized the double test
with the {}
rather than the =
version that I would be preventing the variable test
from being allowed to later be narrowed to an int
.
Is that not how it works?
I've read what's mentioned here and here about integer division, but it's still not clear for me.
If I was working in C I would use type casting:
double test = 0.0;
test = (double)3/2;
printf("test = %f", test);
My impression from reading was that if I did this in C++ it would accomplish the same:
double test {1.2};
test = 3 / 2;