Search code examples
c++c++11initializer-listtype-narrowing

Why is the initializer list allowing type narrowing in C++?


I see two different results while playing with the {} initializer list and primitive types in C++.

I get away only with a warning narrowing conversion of d from double to int inside {}

double d {3.0};
int integer {d};

But if I make it more explicit then, instead of a warning, I get an error narrowing conversion of '3.0e+0' from 'double' to 'int' inside {}

int integer {3.0};

Shouldn't C++11 prevent any narrowing conversion in both cases if {} is used? Then why is it happening only in one case?

I am using the latest version of Eclipse for C/C++ with MingGW. Is there any chance that C++14 has come in the way unintentionally?


Solution

  • With gcc variants you need to specify -Werror=narrowing to make this into error instead of warning. clang and vc++ are more strict and issue an error by default.