C++数据比较警告

mca*_*ner 0 c++ dev-c++ data-comparison

我的程序中有一个WORD变量.

WORD hour;
Run Code Online (Sandbox Code Playgroud)

但是当我比较它时

if(hour>=0 && hour<=18)
{
    hour+=6;
}
Run Code Online (Sandbox Code Playgroud)

由于数据类型的范围有限,它将生成警告 [警告]比较始终为真

我使用Dev-C++作为IDE.

Naw*_*waz 5

if(hour>=0 && hour<=18)
Run Code Online (Sandbox Code Playgroud)

我认为警告是为了比较hour >=0,对于hour类型而言总是如此, WORD这是一种typedef unsigned short(通常),意味着hour总是大于或等于0:

 typedef unsigned short WORD;
Run Code Online (Sandbox Code Playgroud)

在MSVC++上,它是WORD的定义方式,检查编译器是否unsigned存在.如果它是unsigned1,那么hour >=0显然true所有可能的hour.在这种情况下,你需要写这个:

if(hour<=18) //(hour >= 0) is implied by its type
{
    hour+=6;
}
Run Code Online (Sandbox Code Playgroud)

注意无论是unsigned int或是无所谓unsigned short.只要是这样unsigned,hour >=0对所有可能的值都是如此hour.