skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
cpp-narrowing-conversions
This page is read only. You can view the source, but not change it.
# C++ narrowing conversions **[Narrowing conversions](https://en.cppreference.com/w/cpp/language/list_initialization)** are implicit type conversions that may lose information, like converting a larger integer type to a smaller one or `double` to `int`. These are allowed in traditional initialization but prohibited in brace initialization (`{}`), where the compiler rejects them at compile time. Use brace initialization to catch narrowing conversions and prevent accidental data loss. ## Example This example shows how brace initialization prevents narrowing conversions. ```cpp // compile: g++ -o narrow narrow.cpp // run: ./narrow // description: brace initialization prevents narrowing conversions #include <iostream> int main() { // Traditional initialization: allows narrowing (silently loses data) double d = 3.14; int x = d; // implicit conversion: 3.14 -> 3 std::cout << "x = " << x << "\n"; // Brace initialization: rejects narrowing at compile time // int y{d}; // error: narrowing conversion prohibited // Safe conversions are allowed int z{42}; // OK: 42 -> int double w{3.14}; // OK: 3.14 -> double return 0; } ```
Page Tools
Show pagesource
Backlinks
Back to top