user3360310
user3360310

Reputation: 457

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.

Upvotes: 24

Views: 24534

Answers (2)

Simon Karlsson
Simon Karlsson

Reputation: 4129

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;

Upvotes: 10

Arne Mertz
Arne Mertz

Reputation: 24596

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);

Upvotes: 35

Related Questions