How do I avoid narrowing conversions with brace initialization in C++?

Narrowing conversions in C++ occur when a value is converted to a type that cannot represent it without losing information. This can lead to bugs and unexpected behavior in programs. The brace initialization syntax (also known as uniform initialization) introduced in C++11 helps to avoid such narrowing conversions. By utilizing brace initialization, the compiler performs checks to ensure that no narrowing occurs.

Here’s how you can use brace initialization to avoid narrowing conversions:

int x{10}; // OK: initializes x with 10 double y{3.14}; // OK: initializes y with 3.14 int z{2.9}; // Error: narrowing conversion float a{2.9f}; // OK: initializes a with 2.9 int b{1000'000}; // OK: initializes b with 1000000 (C++14)

C++ narrowing conversions brace initialization uniform initialization C++11 C++14