Back to results for “Casting & Conversions”
C++ › Casting & Conversions

What is narrowing conversion and how does brace initialization help?

Intermediate

Answer

A narrowing conversion loses information (e.g., double to int, or a larger int to a smaller one). Brace (list) initialization {} disallows narrowing conversions, turning a silent data-losing conversion into a compile error, which makes initialization safer than the older = or () forms for catching such bugs.
int a = 3.9;   // ok, silently truncates to 3
int b {3.9};   // error: narrowing conversion
Real-world example Using brace initialization catches an accidental double-to-int truncation at compile time.

Common follow-ups: Why does {} reject narrowing? | Give an example of a narrowing conversion.