简体   繁体   中英

C++ Compile Error (comparison between signed and unsigned integer expressions)

I need help regarding to this message:

char_cards.cpp: In member function 'void CHARACTER::Cards_pullout()': char_cards.cpp:88: warning: comparison between signed and unsigned integer expressions

Can somone explain what this error means? I think the problem is with DWORD but i don't know what is wrong.

This is the function:

DWORD CHARACTER::GetEmptySpaceInHand()
{
    for (int i=0; i<MAX_CARDS_IN_HAND; ++i)
    {
        if (character_cards.cards_in_hand[i].type == 0)
            return i;
    }
    return -1;
}
void CHARACTER::Cards_pullout()
{
    DWORD empty_space = GetEmptySpaceInHand(); 
    if (empty_space == -1) // Here is the error.
    {
        #ifdef __MULTI_LANGUAGE_SYSTEM__
        ChatPacket(CHAT_TYPE_INFO, LC_TEXT(GET_LANGUAGE(this), "You don't have space in hands."));
        #else
        ChatPacket(CHAT_TYPE_INFO, LC_TEXT("You don't have space in hands."));
        #endif
        return;
    }
    RandomizeCards();
    SendUpdatedInformations();
}

Initializing an unsigned integer to -1 is well defined and sets the unsigned integer to its maximal value. So using -1 to represent an error condition is OK. To get rid of the warning, you have few options:

1) Use a static_cast . This indicates that you are aware of the conversion and it is intentional:

if empty_space == static_cast<DWORD>(-1)) { ...

2) Use std::numeric_limits<DWORD>::max() instead of -1 . This will require including the limits header.

if (empty_space == std::numeric_limits<DWORD>::max()) { ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM