Udostępnij za pośrednictwem


C6221

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.

See Also

Other Resources

SUCCEEDED

FAILED