Search code examples
c++typesinitializationnarrowing

Type conversion at variable initialization in C++: why using "=" is allowed but "{}" results in error?


Consulting Stroustrup's book "C++ Programming Language 4th Ed", I couldn't understand why the compiler performs the necessary type conversion when using the old "=" atribution way to initialize a variable:

int i1    = 7.2;      // i1 becomes 7 due truncation
bool b1   = 7;        // 7!=0, so b1 becomes true

but would throw an error on the following:

int i2 {7.2};       // error: floating-point to integer conversion
bool b2 {7};        // error: narrowing

Note, the question is not about truncation or narrowing, but what does the language/compiler do differently that one way it "can make it work" but the other don't.

Trying to compile it will result on the following:

error: narrowing conversion of ‘7’ from ‘int’ to ‘bool’ [-Wnarrowing]
   24 |         bool b2{7};

Solution

  • It's due uniform initialization.

    As @marcinj pointed in the comments:

    both int i2=7.2; and bool b1 = 7; could be a coding mistakes causing difficult to find bugs. Uniform initialization can help you find such places quickly at the very beggining.

    Quoting GeeksforGeeks

    Uniform initialization is a feature in C++ 11 that allows the usage of a consistent syntax to initialize variables and objects ranging from primitive type to aggregates. In other words, it introduces brace-initialization that uses braces ({}) to enclose initializer values

    More details at Iso Standard C++11: https://isocpp.org/wiki/faq/cpp11-language#uniform-init