31

I have this problem in my code:

bool CBase::isNumber()
{
return (id & MID_NUMBER);
}

bool CBase::isVar()
{
return (id & MID_VARIABLE);
}

bool CBase::isSymbol()
{
return (id & MID_SYMBOL);
}
8
  • Did you try return (id & MID_NUMBER) > 0;? Commented Jan 4, 2014 at 10:22
  • id or MID_SYMBOL must be of type BOOL. which is just #define to int type in Windows. Your return value is BOOL and it is converted into bool(true or false ). Commented Jan 4, 2014 at 10:23
  • 2
    (id & MID_NUMBER) != 0; is the general way to avoid the warning. Commented Jan 4, 2014 at 10:24
  • 4
    One of the warnings I usually turn off: #pragma warning(disable: 4800)
    – user2249683
    Commented Jan 4, 2014 at 10:24
  • 3
    possible duplicate of What is the performance implication of converting to bool in C++? Commented Jan 4, 2014 at 10:27

3 Answers 3

56

FYI: Casts won't hide the warning by design.

Something like

return (id & MID_NUMBER) != 0;

should clearly state "I want to check whether this value is zero or not" and let the compiler be happy

0
2

Use the !! idiom eg

bool CBase::isNumber()
{
    return !!(id & MID_NUMBER);
}
9
  • 2
    Just to please the compiler !??
    – user2249683
    Commented Jan 4, 2014 at 10:25
  • 9
    @deviantfan The warning itself is useless
    – user2249683
    Commented Jan 4, 2014 at 10:26
  • 1
    @Lücking: Why? Of course the compiler can generate the correct stuff without changed code, but maybe the coder has not intended a implicit cast and finds a semantic error because of the warning?
    – deviantfan
    Commented Jan 4, 2014 at 10:28
  • 1
    First inverts it so you get the inverse of what you actually wanted, second inverts that so you get what you actually wanted. Useful when you have a mix of BOOL (windows), Bool (xwindows) and bool (C++)
    – cup
    Commented Jan 4, 2014 at 10:30
  • 4
    @deviantfan : The warning is not about semantics, it is about performance, which is specious.
    – ildjarn
    Commented Jan 4, 2014 at 10:30
2

Where's the declaration of id and MID_NUMBER? Are you sure they are not windef-style BOOLs rather than (lowercase) bool's? BOOL's have been in windef for decades typedef'd as an int; they pre-date proper C++ bool's and a lot of developers still use them.

Not the answer you're looking for? Browse other questions tagged or ask your own question.