C6220
Note
This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here
warning C6220 - Implicit cast between semantically different integer types: comparing HRESULT to -1. Consider using SUCCEEDED or FAILED macro instead
This warning indicates that an HRESULT
is being compared with an explicit, non-HRESULT
value of -1, which is not a well-formed HRESULT
. A failure in HRESULT
(E_FAIL
) is not represented by a -1. Therefore, an implicit cast of an HRESULT
to an integer will generate an incorrect value and is likely to lead to the wrong result.
Example
In most cases, this warning is caused by the code mistakenly expecting that a function that should return an HRESULT
instead returns an integer, by using –1 as a failure value. The following code sample generates this warning:
#include <windows.h>
HRESULT f( )
{
HRESULT hr;
LPMALLOC pMalloc;
hr = CoGetMalloc(1, &pMalloc);
if (hr == -1)
{
// failure code ...
return E_FAIL;
}
else
{
// success code ...
return S_OK;
}
}
It is best to use the SUCCEEDED
or FAILED
macro to test the value of an HRESULT
. To correct this warning, use the following code:
#include <windows.h>
HRESULT f( )
{
HRESULT hr;
LPMALLOC pMalloc;
hr = CoGetMalloc(1, &pMalloc);
if (FAILED(hr))
{
// failure code ...
return E_FAIL;
}
else
{
// success code ...
return S_OK;
}
}
For this warning, the SCODE
type is equivalent to HRESULT
.
Explicit comparison is appropriate to check for specific HRESULT
values, such as, E_FAIL
. Otherwise, use the SUCCEEDED
or FAILED
macros.
For more information, see SUCCEEDED Macro and FAILED Macro.
Note that the use of malloc and free (and related dynamic memory allocation APIs) have many pitfalls in terms of memory leaks and exceptions. To avoid these kinds of leaks and exception problems altogether, use the mechanisms that are provided by the C++ Standard Template Library (STL). These include shared_ptr, unique_ptr, and vector. For more information, see Smart Pointers and C++ Standard Library.