Search code examples
c++compiler-errorstype-conversionintegerunsigned

conversion from 'unsigned int' to 'int' requires a narrowing conversion


My code includes the following, and I get the error message above based on the last line below.

struct List {
    int word_i;
    int mod_i;
    char mod_type;
    char mod_char;
};

struct Morph {
    Options mode;
    deque<List> search_list;
    vector<string> dictionary;
    vector<bool> discovered;
    string output;
    int sel_word_i = 0;
    bool end_found = 0;
};

// later on in a function:
morph->search_list.push_back({ morph->dictionary.size() - 1, 0, 0, 0 });

Solution

  • You can replace the last line with:

    morph->search_list.emplace_back( morph->dictionary.size() - 1, 0, 0, 0 );
    

    Thus the object is created not through brace initialization which does not allow narrowing conversion.

    The narrowing conversion is from the return value of the call to size which returns std::size_t which is unsigned.

    For why size() - 1 is not converted to a signed value see: C++ Implicit Conversion (Signed + Unsigned)