How to avoide BOOL to bool performance warning?

18 05 2008


Many of the windows apis are using BOOL for boolean value which is actually a typedef of int. Its been used, because during old C days bool was not a built-in datatype. Now a days since C++ supports built-in bool, often we need to convert the BOOL to bool. For instance see code snippet below

BOOL bResult = FALSE;
...
bool bReturnValue = bResult;

But it will give you a perfoamnce warning – “warning C4800: ‘int’ : forcing value to bool ‘true’ or ‘false’ (performance warning)”. Because internally an int is converted to bool. But since our clients need “0 errors, 0 warnings” we’ve to avoid this warning. Its pretty simple.


you can make use of the operator != which will return bool. See the code snippet below.

BOOL bResult = FALSE;
...
bool bReturnValue = (bResult != FALSE);

Another interesting one is it can be used to reduce code unwanted code blots. See the following code block. Its a typical usage by most of us.

bool Function()
{
    // Member which holds return in bool.
    bool bReturn = false;

    // Assume FnWhichReturnsBOOL is a function
    // which returns BOOL.
    if( FALSE != FnWhichReturnsBOOL())
    {
        // Since its success, set return as true.
        bReturn = true;
    }

    return bReturn;
}

This can be easly re-written as follows

bool Function()
{
    BOOL bReturn = FnWhichReturnsBOOL();
    return bReturn != FALSE;
}


Wanna read more? check out this link in MSDN – http://msdn.microsoft.com/en-us/library/b6801kcy(VS.71).aspx


Targeted Audience – Intermediate.