Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Cast between semantically different integer types: HRESULT to a Boolean type
This warning indicates that an HRESULT
is being cast to a Boolean type. The success value (S_OK
) of an HRESULT
equals 0. However, 0 indicates failure for a Boolean type. Casting an HRESULT
to a Boolean type and then using it in a test expression will yield an incorrect result.
Remarks
Sometimes, this warning occurs if an HRESULT
is being stored in a Boolean variable. Any comparison that uses the Boolean variable to test for HRESULT
success or failure could lead to incorrect results.
Code analysis name: CAST_HRESULT_TO_BOOL
Example
The following code generates warning C6214:
#include <windows.h>
BOOL f( )
{
HRESULT hr;
LPMALLOC pMalloc;
hr = CoGetMalloc(1, &pMalloc);
if ((BOOL)hr) // warning C6214
{
// success code ...
return TRUE;
}
else
{
// failure code ...
return FALSE;
}
}
To correct this warning, use the following code:
#include <windows.h>
BOOL f( )
{
HRESULT hr;
LPMALLOC pMalloc;
hr = CoGetMalloc(1, &pMalloc);
if (SUCCEEDED(hr))
{
// success code ...
return TRUE;
}
else
{
// failure code ...
return FALSE;
}
}
For this warning, the SCODE
type is equivalent to HRESULT
.
Usually, the SUCCEEDED
or FAILED
macro should be used to test the value of an HRESULT
.
For more information, see one of the following articles:
To make use of modern C++ memory allocation methodology, use the mechanisms that are provided by the C++ Standard Library (STL). These include shared_ptr
, unique_ptr
, and containers such as vector
. For more information, see Smart pointers and C++ Standard Library.