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)
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?