C++ 编译错误(有符号和无符号整数表达式的比较)

标签 c++

我需要有关此消息的帮助:

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

有人能解释一下这个错误是什么意思吗?我认为问题出在 DWORD 上,但我不知道出了什么问题。

这是函数:

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();
}

最佳答案

将无符号整数初始化为 -1定义明确并将无符号整数设置为其最大值。所以用-1来表示错误条件是可以的。要消除警告,您有几种选择:

1) 使用 static_cast .这表示您知道转换并且是有意的:

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

2) 使用std::numeric_limits<DWORD>::max()而不是 -1 .这将需要包括 limits标题。

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

关于C++ 编译错误(有符号和无符号整数表达式的比较),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44097409/

相关文章:

c++ - 错误 c2440 '=' 无法从 int * 转换为 Type<T> *

c++ - 使用 cmake 制作项目源目录的头文件后代

c++ - Ubuntu 14.04TLA 上的代码块和 Gtkmm

c++ - 什么是 "cerr"和 "stderr"?

c++ - 将第一个派生类转换为第二个派生类 - 为什么它有效?

c++ - 如何使用多线程正确挂接 WinInet?

c++ - 避免输出交错

c++ - C++ 中的析构函数

c++ - VBA 到 C++ dll 函数调用,如何缺少参数

具有基类的 C++ 唯一静态 ID 和类名