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

102 Views Asked by At

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};
2

There are 2 best solutions below

0
jonathask On BEST ANSWER

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

0
tbxfreeware On

Video Resources

Indeed, the problem was a misunderstanding of what uniform initialization is all about.

Here are some video resources that helped me get a focused understanding of initialization in C++. These are talks given by Timur Doumler and Nicolai Josuttis.

I like them both, but the talk by Timur Doumler does a better job explaining the differences between the various kinds of initialization. The talk by Nicolai Josuttis is more results oriented, but brushes over some of the detail.

YouTube has four different versions of the talk by Timur Doumler. They are all roughly the same, so pick one. I have not seen the last one, but perhaps I would start with it. Presumably, it has some of the kinks worked out.

CppCon 2018 – Nicolai Josuttis – "The Nightmare of Initialization in C++” (1:00)
Meeting C++ 2018 – Timur Doumler – "Initialization in modern C++" (1:01)
C++ on Sea 2019 – Timur Doumler – "Initialisation in modern C++ " (1:04)
Core C++ 2019 – Timur Doumler – "Initialisation in modern C++" (1:01)
C++ User Group (Russia) – Timur Doumler – "Initialisation in modern C++" (1:00)