Why is const int fine for char brace init?
Asked Answered
L

1

14

I thought brace initialization doesn't allow narrowing. But why is int const allowed for char brace initialization?

int value1 = 12;
char c1{value1};  // error! no narrowing

const int value2 = 12;
char c2{value2};   // why is this fine?

See it on Godbolt.

Latimore answered 9/9, 2019 at 13:37 Comment(1)
Which compiler and which options are you using? It depends on this as well!Shading
C
17
const int value2 = 12;

value2 is a compile-time constant. The compiler can easily (and has to) prove that the value is 12 which happens to be within the range of values representable by char.

int value1 = 12;

value1 is not a compile-time constant. The value of the variable could change at runtime.

The exact wording of the standard rule (quoting latest draft, emphasis added):

[dcl.init.list]/7

A narrowing conversion is an implicit conversion

  • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.
Crystlecs answered 9/9, 2019 at 13:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.