Domanda

I have one WORD variable in my program.

WORD hour;

But when I compare It

if(hour>=0 && hour<=18)
{
    hour+=6;
}

It will generate warning [Warning] comparison is always true due to limited range of data type

I am using Dev-C++ as IDE.

È stato utile?

Soluzione

if(hour>=0 && hour<=18)

I think the warning is for the comparison hour >=0 which is always true for hour is of type WORD which is a typedef of unsigned short (usually) which means hour is always greater than or equal to 0:

 typedef unsigned short WORD;

On MSVC++ it is how WORD is defined, check your compiler if it is unsigned or not. If it unsigned1, then hour >=0 is obviously true for all possible values of hour. In that case, you need to write just this:

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

1. Note that it doesn't matter whether is unsigned int or unsigned short. As long as it is unsigned, hour >=0 will be true for all possible values of hour.

Altri suggerimenti

It seems that WORD is typedef-ed somewhere as unsigned integer type, so it will always be positive number (>=0). So the first comparison is always true.

Depending on what data type WORD is (since you haven't provided it, I assume it is unsigned short), the first comparison is always true since no negative integers fit in an unsigned short. So the compiler told you that the first comparison is more or less, pointless.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top