Site Tools


wiki:cpp-narrowing-conversions

C++ Narrowing conversions

Narrowing conversions 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.

// 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;
}
wiki/cpp-narrowing-conversions.md · Last modified: by 127.0.0.1