Does someone knows why this compiles without warnings
int main()
{
const int i = 1024;
std::initializer_list<size_t> i_l = { i }; // no warning
return 0;
}
but does not
int main()
{
const int i = pow(2,10);
std::initializer_list<size_t> i_l = { i }; // warning
return 0;
}
Warning:
non-constant-expression cannot be narrowed from type 'int' to 'unsigned long' in initializer list [-Wc++11-narrowing]
std::initializer_list<size_t> i_l = { i }; i_l = i_l; // warning
Quoting the same section as from your previous question, [dcl.init.list]:
What counts as a constant expression? That is defined in [expr.const]:
So,
i
is a constant expression inconst int i = 1024;
becausei
is a non-volatile
const
object of integral type initialized with a constant expression (1024
). But in the second example,pow()
isn't a constant expression because it's an invocation of a non-constexpr
function.Hence, the first example doesn't count as narrowing but the second does. You can think of it as the compiler knows that 1024 is fine, but doesn't know that pow(2, 10) is.