C6221

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 C6221: Implicit cast between semantically different integer types: comparing HRESULT to an integer. Consider using SUCCEEDED or FAILED macros instead

This warning indicates that an HRESULT is being compared to an integer other than zero. A success in HRESULT (S_OK) is represented by a 0. Therefore, an implicit cast of an HRESULT to an integer will generate an incorrect value and is likely to lead to the wrong result. It is often caused by mistakenly expecting a function to return an integer when it actually returns an HRESULT.

Example

The following code generates this warning by comparing HRESULT against an integer value:

#include <windows.h>  
  
HRESULT f( )  
{  
  HRESULT hr;  
  LPMALLOC pMalloc;  
  
  hr = CoGetMalloc(1, &pMalloc);  
  if (hr == 4)  
  {  
    // failure code ...  
    return S_FALSE;  
  }  
  else  
  {  
    // success code ...  
    return S_OK;  
  }  
}  

To correct this warning, the following code uses the FAILED macro:

#include <windows.h>  
  
HRESULT f( )  
{  
  HRESULT hr;  
  LPMALLOC pMalloc;  
  
  hr = CoGetMalloc(1, &pMalloc);  
  if (FAILED(hr))  
  {  
    // failure code ...  
    return S_FALSE;  
  }  
  else  
  {  
    // success code ...  
    return S_OK;  
  }  
}  

For this warning, the SCODE type is equivalent to HRESULT.

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.