Currently I was self-learning C++ primer 5th edition. The text says:
When used with variables of built-in type, this form of initialization has one important property: The compiler will not let us list initialize variables of built-in type if the initializer might lead to the loss of information:
Here is the example code:
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
But when I tried it myself on C++shell:
long double a=3.14159265354;
int b(a);
int c{a};
std::cout<<a<<std::endl<<b<<std::endl<<c<<std::endl;
It simply gives a warning of -Wnarrowing
but the program successfully executed. Why?
The Standard specifies that a diagnostic is required in case that a program is ill-formed. Which is the case when a narrowing-conversion takes place inside a braced-initializer.
That is, the standard doesn't distinguish between an error and a warning.
1.3.6 diagnostic message [defns.diagnostic]
message belonging to an implementation-defined subset of the implementation's output messages
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With