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 isn't a well-formed HRESULT.

Remarks

A failure in HRESULT (E_FAIL) isn't 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.

Code analysis name: COMPARING_HRESULT_TO_MINUS_ONE

Example

In most cases, warning C6220 is caused by code that mistakenly expects a function to return an integer, and to use -1 as a failure value, but instead the function returns an HRESULT. 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's 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.

The use of malloc and free (and related dynamic memory allocation APIs) has many pitfalls in terms of memory leaks and exceptions. To avoid these kinds of potential leaks altogether, 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.