Search code examples
c++dev-c++data-comparison

C++ warning of data comparision


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.


Solution

  • 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.