23
votes

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.

2
Why don't you use bool instead of BOOL as a return value in the first place?Henrik
@Henrik if user3360310 has not adopted Microsoft's "prefix-everything-with-C" notation, CPlan looks much like a class from some MS library, so the signature cannot be changed.Arne Mertz

2 Answers

31
votes

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

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;