Search code examples
c++expressionunsignedsigned

C++: warning: Signed and unsigned expression ( Gmake, freebsd )


I'm facing a little problem and I hope you can help me. Thank you.

Here is the error code:

FILE.cpp: In member function 'bool DragonSoulTable::ReadAdditionalApplys()':
FILE.cpp:223: warning: comparison between signed and unsigned integer expressions

And here is the code I put on pastebin because it is too big to put that code on forum FILE.CPP


Solution

  • Go to line 223, you have:

    for (int i = 0; i < m_vecDragonSoulNames.size(); i++)
    

    As you can see, i is of type int but does m_vecDragonSoulNames.size() return an int??

    In fact, you have a lot of comparisons like this in your code.

    Compilers give warnings (not errors) when you compare signed and unsigned types, this is because the ranges of this types are different. And there are good reasons for this, if you dont be careful the results can be surprising...

    If you know its safe to make such a comparison, you can explicitly cast one of the values to be of the same type of the other, and the warning will dissapear.

    Something like:

    unsigned int a = someUnisgnedValue;
    int b = someSignedValue; 
    if ((unsigned) b < a)    
       //... do something
    

    Or you can just use both of the same type. For example in the line 223 of your code you can do:

    for (unsigned int i = 0; i < m_vecDragonSoulNames.size(); i++)
    

    Please, check this other question: When to use unsigned values over signed ones?