5

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?

Des1gnWizard
  • 477
  • 1
  • 4
  • 13
  • 1
    In general, for violations of the language rules, the C++ standard requires that the compiler issue a diagnostic. It did that. The standard does not distinguish between warnings and errors, and does not require any particular behavior after issuing the diagnostic. – Pete Becker Dec 22 '15 at 14:53
  • @PeteBecker Oh, thank you for point it out! – Des1gnWizard Dec 22 '15 at 14:53
  • @NathanOliver I did try to find out the answer on FAQ but it's so difficult considering his question title. Anyway next time I will try to be more careful. – Des1gnWizard Dec 22 '15 at 15:02

1 Answers1

2

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

101010
  • 41,839
  • 11
  • 94
  • 168