6
votes

Can anyone please explain to me, why the compiler allows initialize variables of built-in type if the initializer might lead to the loss of information?

For example C++ Primer, the 5th edition says, that The compiler will not let us list initialize variables of built-in type if the initializer might lead to the loss of information.

but my compiler gcc v 4.7.1 initialized variable a in the following code successfully:

long double ld = 3.1415926536; 
int a{ld};

there was just warning: narrowing conversion of ‘ld’ from ‘long double’ to ‘int’ inside { } [-Wnarrowing].

3
I would say the book is wrong. C and C++ are very lax with that kind of things...Matthieu M.
@MatthieuM. C++11 isn't.rubenvb
n3337 4.9/1 [conv.fpint] A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type. So conversion is possible and actually defined in the Standard, what is unclear is whether it's allowed or not here, and I did not yet found anything about that.Matthieu M.
n3337 8.5.4/3 [dcl.init.list]: Otherwise, if the initializer list has a single element, the object or reference is initialized from that element; if a narrowing conversion (see below) is required to convert the element to T, the program is ill-formed. I don't see the ambiguity.rubenvb

3 Answers

11
votes

One of the features of initializer lists is that narrowing conversions are not allowed. But the language definition doesn't distinguish between warnings and errors; when code is ill-formed it requires "a diagnostic", which is defined as any message from a set of implementation-defined messages. Warnings satisfy this requirements. That's the mechanism for non-standard extensions: having issued a warning, the compiler is free to do anything it wants to, including compiling something according to implementation-specific rules.

2
votes

You can set the compiler flag to flag all warnings as error. In that case only it will stop you from doing like that. Otherwise it will only be a warning.

0
votes

This issue has been coming up lately. With gcc-4.7 a command line switch turns on the required behaviour:

g++ -Werror=narrowing ...