Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Narrowing conversion of list initialization is an error or just a warning? [duplicate]

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 -Wnarrowingbut the program successfully executed. Why?

like image 260
Des1gnWizard Avatar asked Oct 30 '22 12:10

Des1gnWizard


1 Answers

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

like image 126
101010 Avatar answered Nov 02 '22 23:11

101010