Warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)
Asked Answered
C

3

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);
}
Counterforce answered 4/1, 2014 at 10:20 Comment(8)
Did you try return (id & MID_NUMBER) > 0;?Aretha
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 ).Williamson
Why not !=0 instead of >0. And no, bool it not BOOLHandiwork
(id & MID_NUMBER) != 0; is the general way to avoid the warning.Jermyn
One of the warnings I usually turn off: #pragma warning(disable: 4800)Pretext
I took your title and put it into Google, several of the first results explain the warning.Isaacson
possible duplicate of What is the performance implication of converting to bool in C++?Jermyn
Why not accept Marco's answer?Ionosphere
V
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

Venusberg answered 4/1, 2014 at 10:28 Comment(0)
S
2

Use the !! idiom eg

bool CBase::isNumber()
{
    return !!(id & MID_NUMBER);
}
Seabrook answered 4/1, 2014 at 10:24 Comment(9)
Just to please the compiler !??Pretext
And why 2 ops instead of 1 (even if it is optimized)?Handiwork
@Dieter Lücking: Non-standard workarounds are probably worse.Handiwork
@Handiwork The warning itself is uselessPretext
@DieterLucking: It can not be useless as it is warning.Williamson
@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?Handiwork
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++)Seabrook
@Handiwork : The warning is not about semantics, it is about performance, which is specious.Rarefied
I give you a +1. This was useful for me, since I have this warning in templated code where I cannot compare against 0 but !! works.Mantellone
R
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.

Romina answered 22/9, 2014 at 9:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.