Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning C4800: 'BOOL' : forcing value to bool 'true' or 'false' (performance warning)

When I compile the below code snippet code in Visual studio 2008, I get this warning.

BOOL
CPlan::getStandardPlan() const
{
    return m_standardPlan;
}


bool m_bStandardPlan;

if(plan!=NULL)
{
    // Assign the values to the Cola object
    poCola->m_lPlanId           = plan->getPlanId();
    poCola->m_lPlanElementId        = plan->getPlanElementId();
    poCola->m_lPlanElementBaseId        = plan->getPlanElementBaseId();
    poCola->m_bStandardPlan         = plan->getStandardPlan(); //C4800

    return 1;
}

I referred the following links,

http://msdn.microsoft.com/en-us/library/b6801kcy%28v=vs.90%29.aspx

Forcing value to boolean: (bool) makes warning, !! doesnt

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

I'm not sure how to fix this warnings.

like image 639
user3360310 Avatar asked Mar 19 '14 07:03

user3360310


2 Answers

BOOL is a typedef for int somewhere in WinAPI. WinAPI is a C API, so they can't use C++'s bool. If you can't get rid of it by returning a bool from the function, e.g. because you don't maintain the function, then you can use an explicit check against zero to get rid of the warning:

poCola->m_bStandardPlan = (plan->getStandardPlan() != 0);

Another consideration would be to add a function that encapsulates the check:

bool getStandardPlan(CPlan const& plan) {
  return plan->getStandardPlan() != 0;
}

and then

poCola->m_bStandardPlan = getStandardPlan(plan);
like image 82
Arne Mertz Avatar answered Oct 16 '22 09:10

Arne Mertz


getStandardPlan() returns a BOOL which actually is a typedef of an int (0 is interpeted as false and all other values as true). I usually solve this issue with the ternary operator.

poCola->m_bStandardPlan = plan->getStandardPlan() ? true : false;
like image 37
Simon Karlsson Avatar answered Oct 16 '22 08:10

Simon Karlsson